-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwap nodes in pairs
121 lines (86 loc) · 3.34 KB
/
Swap nodes in pairs
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
https://leetcode.com/problems/swap-nodes-in-pairs/
------------------------------------RECURSIVE SOLUTION----------------------------------------
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL)return NULL;
if(head -> next == NULL){
return head;
}
// 1 -> 2 -> 3 -> 4
// After swapping = 2 -> 1 -> 4 -> 3
// 1. Think.... what will be the newhead after the swapping nodes in pairs ?
// --> Assign newhead pointer
// 2. Now , What should we do - either swap the current pair or recurse first ?
// --> If we swap the current pair (1 -> 2 ==> 2 -> 1) then we will never be able to traverse furthur
// Therefore, we will recurse first.
// Expectation - we will return newhead after swapping nodes in pairs
// faith - we will assume that , we'll get head with all pairs are swapped except the current one.
// faith to expectation - we just swap the current pair and return the newhead;
ListNode* newhead = head -> next;
head -> next = swapPairs(newhead -> next);
newhead -> next = head;
return newhead;
}
};
--------------------- Think of iterative sol ----------------------------------
/*
#---->@---->@---->@---->@---->@---->@
^ ^
pre cur
1. pre->next = cur->next
__________
/ \
#---->@---->@ @---->@---->@---->@
^ ^
pre cur
2. pre = pre->next
__________
/ \
#---->@---->@ @---->@---->@---->@
^ ^
cur pre
3. cur->next = pre->next
__________
/ \
#---->@---->@ @ @---->@---->@
\_________/
^ ^
cur pre
4. pre->next = cur
__________
/ \
#---->@---->@ @<----@ @---->@
\_________/
^ ^
cur pre
5. pre = cur; cur = cur->next
__________
/ \
#---->@---->@ @<----@ @---->@
\_________/
^ ^
pre cur
------------------- code ------------------
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL)return NULL;
if(head -> next == NULL){
return head;
}
ListNode* curr = head;
ListNode* temp = new ListNode(0);
temp -> next= head;
ListNode* prev = temp;
while(curr and curr -> next){
prev -> next = curr -> next;
prev = prev -> next;
curr -> next = prev -> next;
prev -> next = curr;
prev= curr;
curr = curr -> next;
}
return temp -> next;
}
};