做这道题需要画图来做,否则几个指针很容易将自己搞混淆。借助代码随想录中的图进行记录。
操作前:
操作后:
代码如下:
/**
* 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);
dummyhead->next = head;
ListNode * cur = dummyhead;
while(cur->next != NULL && cur->next->next != NULL){
ListNode * tmp1 = cur->next;
ListNode * tmp2 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp1;
cur->next->next->next = tmp2;
cur = cur->next->next;
}
head = dummyhead->next;
delete dummyhead;
return head;
}
};