这里是使用另一种方式实现单链表的代码,仍然保持插入位置规则不变:
#ifndef NULL
#define NULL 0
#endif
#include<iostream>
using namespace std;
//定义单链表结点结构
struct LNode
{
int data;
LNode* next;
LNode() {};
LNode(int e, LNode* n = NULL) :data(e), next(n) {};
};
//单链表list类创建
class List
{
protected:
LNode* head;
int _size;
public:
//构造函数
List() {
head = new LNode();
head->next = NULL;
_size = 0;
}
//析构函数
~List() {
clear();
delete head;
head = NULL;
};
//清空链表
void clear()
{
LNode* p = head->next;
while (p != NULL)
{
LNode* temp = p->next;
delete p;
p = temp;
}
head->next = NULL; // 清空后头结点指针为空指针
_size=0; // 更新大小为零
}
//头插法
void insert(int e)
{
_size++;
LNode* p = new LNode(e);
p->next = head->next;
head->next=p;
};
void insert(int index, int a)
{
if (index < 1 || index > _size + 1)
{
return; // 无效的插入位置,直接返回
}
_size++;
LNode* p = head;
// 移动 p 到要插入位置的前一个节点
for (int i = 1; i < index; i++)
{
p = p->next;
}
LNode* tmp = new LNode(a);
tmp->next = p->next;
p->next = tmp;
}
void print_L()
{
LNode* p = head->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int change()
{
int x, y;
cin >> x >> y;
if (x<0 || x>_size || y<0 || y>_size)
{
cout << "error" << endl;
return -1;
}
// 找到第 x 和第 y 个结点的前驱结点
LNode* px_pre = head;
for(int i=0;i<x-1;++i){
px_pre=px_pre->next;
}
LNode* py_pre=head;
for(int i=0;i<y-1;++i){
py_pre=py_pre->next;
}
// 获取第 x 和第 y 个结点
LNode* px=px_pre->next;
LNode* py=py_pre->next;
// 交换两个结点
px_pre -> next=py;
py_pre -> next=px;
// 更新两个结点后面的指针
LNode *tpx_next,*tpy_next;
tpx_next=px->next;
tpy_next=py->next;
px->next=tpy_next;
py->next=tpx_next;
return 0;
};
};
int main()
{
List LB;
int n, a;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a;
LB.insert(i + 1, a);
}
LB.print_L();
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
int a = LB.change();
if (a == -1)
continue;
LB.print_L();
}
return 0;
}
这个代码使用了一个头结点和指针操作来实现单链表的插入和交换操作。
内容由零声教学AI助手提供,问题来源于学员提问