重新编写的代码如下所示:
#include<iostream>
using namespace std;
//定义单链表结点结构
struct ListNode {
int data;
ListNode* next;
ListNode(int val) : data(val), next(nullptr) {}
};
//单链表类创建
class LinkedList {
private:
ListNode* head;
public:
//构造函数
LinkedList() : head(nullptr) {}
//析构函数
~LinkedList() {
ListNode* curr = head;
while (curr) {
ListNode* temp = curr;
curr = curr->next;
delete temp;
}
}
//头插法
void insert(int value) {
ListNode* newNode = new ListNode(value);
if (head == nullptr) {
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
}
//在指定位置插入元素
void insert(int index, int value)
{
if (index < 1 || index > size()+1)
return; // 无效的插入位置,直接返回
ListNode** curr = &head;
for (int i = 1; i < index; ++i)
curr = &((*curr)->next);
ListNode* newNode = new ListNode(value);
newNode->next = *curr;
*curr = newNode;
}
int size()
{
int count=0;
ListNode* curr=head;
while(curr)
{
++count;
curr=curr->next;
}
return count;
}
void printList()
{
ListNode *temp=head;
while(temp!=nullptr)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
void swap(int x, int y) {
if (x < 0 || x > size() || y < 0 || y > size()) {
cout << "error" << endl;
return;
}
ListNode** currX = &head;
for (int i = 0; i < x; ++i)
currX = &((*currX)->next);
ListNode** currY = &head;
for (int i = 0; i < y; ++i)
currY = &((*currY)->next);
ListNode* tempX = *currX;
*currX = (*currX)->next;
ListNode* tempY = *currY;
*currY = (*currY)->next;
tempX->next = tempY->next;
tempY->next = tempX;
}
};
int main() {
LinkedList list;
int n, a;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a;
list.insert(i + 1, a);
}
list.printList();
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
int x, y;
cin >> x >> y;
list.swap(x, y);
list.printList();
}
return 0;
}
这个版本使用了更清晰的类名和成员函数命名,并且修正了一些代码逻辑错误。
内容由零声教学AI助手提供,问题来源于学员提问




