题目:
代码(首刷看解析 2024年1月12日):
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==nullptr) return nullptr;
ListNode* cur = new ListNode(0,head);
ListNode* dummy = cur;
while(cur->next != nullptr && cur->next->next != nullptr) {
ListNode* tmp = cur->next;
ListNode* tmp2 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
tmp->next = tmp2;
cur = cur->next->next;
}
return dummy->next;
}
};
链表类题目一定要画图
代码(二刷看思路 2024年3月4日)
有时候图画对了,代码不一定写的对,这题单指针要比双指针简单
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0, head);
ListNode* cur = dummyHead;
while (cur->next && cur->next->next) {
ListNode* N1 = cur->next;
ListNode* N2 = cur->next->next;
// 变换
cur->next = N2;
N1->next = N2->next;
N2->next = N1;
cur = cur->next->next;
}
return dummyHead->next;
}
};
代码(三刷自解 2024年4月11日)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0, head);
ListNode* cur = dummyHead;
ListNode* left;
ListNode* right;
while (cur->next && cur->next->next) {
left = cur->next;
right = cur->next->next;
// 开始变向
left->next = right->next;
cur->next = right;
right->next = left;
cur = left;
}
return dummyHead->next;
}
};
代码(四刷自解 2024年4月16日 BUGFREE)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
// 每次交换,获得交换前的节点
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
while (cur->next && cur->next->next) {
// 交换
ListNode* N1 = cur->next;
ListNode* N2 = N1->next;
N1->next = N2->next;
cur->next = N2;
N2->next = N1;
//更新cur
cur = N1;
}
return dummy->next;
}
};