leetCode_swap_pairs

background

LeetCode24: swap pairs

intuitive sol

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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) {}
};
#include <iostream>
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummy = new ListNode(-1);
ListNode *prev = dummy ;
prev->next = head ;
ListNode *p1=head, *p2=p1->next, *p3=p2->next, *p4=p3->next, *pn, *tmp ;
if(p1 == nullptr)
{
return nullptr ;
}else if(p2 == nullptr){
return p1 ;
}else if(p3 == nullptr)
{
p2->next = p1 ;
p1->next = nullptr ;
head = p2 ;
return head ;
}else if(p4 == nullptr)
{
head->next = p2 ;
p2->next = p1 ;
p1 ->next = p3;
return head ;
}
for(p1=head, p2=p1->next, p3=p2->next, p4=p3->next ; p4 && p3 && p2 && p1; prev=p3, p1=prev->next, p2=p1->next, p3=p2->next, p4=p3->next )
{
pn = p4->next ;
p2->next = p1 ;
p4->next = p3 ;
p1->next = p4;
p3->next = pn ;
prev->next = p2 ;
if (pn == nullptr)
{
break;
}else if(pn->next == nullptr)
{
break;
}else if (pn->next->next == nullptr)
{
break;
}else if(pn->next->next->next == nullptr)
{
break;
}
}
if(pn == nullptr || pn->next == nullptr){
return prev->next;
}
if(pn->next->next == nullptr )
{
tmp = pn->next ;
prev->next = pn->next ;
tmp->next = pn ;
pn->next = nullptr;
}else if(pn->next->next->next == nullptr){
tmp = pn->next ;
ListNode *last = tmp->next ;
prev->next = tmp ;
pn->next = last ;
}
return prev->next;
}
};
int main()
{
ListNode *head = new ListNode(1);
ListNode *sec = new ListNode(2);
ListNode *thd = new ListNode(3);
ListNode *fth = new ListNode(4);
head->next = sec ;
sec->next = thd ;
thd->next = fth ;
Solution *sol = new Solution();
ListNode *res = sol->swapPairs(head) ;
std::cout << res->val << ', ' << res->next->val << ', ' << res->next->next->val << std::endl;
return 0;
}