下面是使用另一种方法实现的代码:
#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;
void init() {
head = new LNode;
head->next = NULL;
_size = 0;
}
public:
//构造函数
List(){init();}
//析构函数
~List() {
LNode* p = head->next;
while (p)
{
LNode* tmp = p->next;
delete p;
p = tmp;
}
delete head; // 删除头节点
head = NULL; // 将头节点指针置为空指针,防止悬空指针的问题
_size = 0; // 链表长度置为0
};
// 头节点不存储信息,所以删除 info() 函数
//修改头插法 insert 函数,使用传入参数 a 的引用进行操作(方便外部代码使用)
void insert(int& a)
{
_size++;
LNode* p = new LNode(a,head->next);
head->next = p;
}
// 修改 print_L 函数,去除头节点的数据输出
void print_L()
{
LNode* p = head->next; // 头节点的下一个节点开始遍历输出
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
// 修改 change 函数,使用传入参数 x、y 的引用进行操作(方便外部代码使用)
int change(int& x, int& y)
{
if (x<0 || x>_size || y<0 || y>_size)
{
cout << "error" << endl;
return -1;
}
LNode* p = head->next; // 头节点的下一个节点开始遍历查找第 x 个节点
LNode* s = head->next; // 头节点的下一个节点开始遍历查找第 y 个节点
for (int i = 1; i < x; i++)
{
p = p->next;
}
LNode* tmp1 = p->next;
p->next = tmp1->next;
for (int j = 1; j < y; j++)
{
s = s->next;
}
tmp1->next = s->next;
s->next = tmp1;
return 0;
}
};
int main()
{
List LB;
int n, a;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a;
LB.insert(a);
}
LB.print_L();
int t, x, y;
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> x >> y;
if (LB.change(x, y) == -1)
continue;
LB.print_L();
}
}
这里对头插法 insert()
函数和节点的遍历操作进行了修改,使其更符合传入引用参数的使用方式。同时还对 print_L()
和 change()
函数做了相应的修改以适应新的数据结构定义。
内容由零声教学AI助手提供,问题来源于学员提问