
1.jpg

2.jpg

3.jpg
struct ListNode {
int val;
ListNode* next;
ListNode(int x): val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* swapListNode(ListNode* head) {
ListNode* dummy = new ListNode(0); // 创建虚拟头节点
dummy->next = head; // 将虚拟头节点指向head,这样方面以后做删除头节点操作
ListNode* cur = dummy;
while(cur->next != nullptr && cur->next->next != nullptr) {
ListNode* tmp = cur->next; // 记录临时节点
ListNode* tmp1 = cur->next->next->next;
cur->next = cur->next->next; // 第1步
cur->next->next = tmp; // 第2步
cur->next->next->next = tmp1; // 第3步
cur = cur->next->next;
}
return dummy->next;
}
};