以下是使用另一种方法实现该代码的单链表:
”`cpp #ifndef NULL #define NULL 0 #endif
#include
// 定义单链表结点结构 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() {
while (head) {
LNode* p = head->next;
delete head;
head = p;
}
}
// 头节点
List(int info) {
head = new LNode(info);
_size = 0;
}
int& info() { return head->data; } // 返回链表头结点的信息
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* tmp = new LNode(a);
if (index == 1) {
tmp->next = head->next;
head->next= tmp;
return;
}
LNode* pre = nullptr, * cur = head->next;
int count = 1;
while (count < index) {
pre = cur;
cur = cur->next;
count++;
}
tmp->next = cur;
pre->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;
}
if (x == y)
return 0;
LNode* px_prev = nullptr, * py_prev = nullptr, * px, * py;
// 寻找第 x 个结点和它的前驱
int count_x = 0;
px_prev = head;
while (count_x < x - 1) {
px_prev = px_prev->next;
count_x++;
}
px = px_prev->next;
// 寻找第 y 个结点和它的前驱
int count_y = 0;
py_prev = head;
while (count_y < y - 1) {
py_prev= py_prev -> next;
count_y++;
}
py= py_ prev -> next;
// 进行交换操作
LNode* temp=px- > next;//保存px之后的结点,以便于重新链接;
px- > next= py- > next;
py_prev -> next= px;
py- > next=temp;
px_ prev ->next = py;
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();
}
}
“`
内容由零声教学AI助手提供,问题来源于学员提问