-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24.cpp
46 lines (46 loc) · 1.3 KB
/
24.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* 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 { // recursion
public:
ListNode* swapPairs(ListNode* head) {
function<ListNode*(ListNode*, ListNode*, ListNode*)> swap =
[&swap](ListNode* a, ListNode* b, ListNode* cur) {
if (a && b) {
b->next = a;
a->next = cur;
}
if (cur && cur->next)
a->next = swap(cur, cur->next, cur->next->next);
return b;
};
if (head && head->next)
return swap(head, head->next, head->next->next);
return head;
}
};
class Solution2 { // iteration
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next)
return head;
auto h = ListNode(0, head);
auto p = &h;
while (p->next && p->next->next) {
auto l = p->next, r = p->next->next;
auto next = r->next;
p->next = r;
r->next = l;
l->next = next;
p = l;
}
return h.next;
}
};