LeetCode Hot100 NO.24

Problem

https://leetcode.cn/problems/swap-nodes-in-pairs/description/?envType=study-plan-v2&envId=top-100-liked

Solution

两两交换链表中的节点
pre->p1->p2->p3 => pre->p2->p1->p3
设置一个dummy节点避免对头节点的特殊处理,遍历整个链表完成上面的操作,遍历过程要保证p1p2非空
可以只记录p2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 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 dummy(0, head);

ListNode *pre = &dummy;

while (pre->next && pre->next->next)
{
ListNode *p2 = pre->next->next;
pre->next->next = p2->next;
p2->next = pre->next;
pre->next = p2;

pre = pre->next->next;
}

return dummy.next;
}
};