-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path24. Swap Nodes in Pairs.cpp
120 lines (70 loc) · 2.31 KB
/
24. Swap Nodes in Pairs.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
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
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes
(i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Constraints:
The number of nodes in the list is in the range [0, 100].
0 <= Node.val <= 100
********************************************************************************
# Approach 1: Swap the values inside the node (violates the problem statement)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode *curr = head;
while (curr && curr->next) {
swap(curr->val, curr->next->val);
curr = curr->next->next;
}
return head;
}
};
TC -> O(n), n is the length of the linked list
SC -> O(1)
********************************************************************************
# Approach 2: Iterative swap actual nodes
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode *prev = NULL, *curr = head, *ahead = head->next;
head = head->next; // new updated head
while (curr && ahead) {
if (prev) prev->next = ahead;
curr->next = ahead->next;
ahead->next = curr;
prev = curr;
curr = curr->next;
if (curr) ahead = curr->next;
}
return head;
}
};
TC -> O(n), n is the length of the linked list
SC -> O(1)
********************************************************************************
# Approach 3: Recursive swap actual nodes
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode *curr = head, *tmp = NULL;
if (curr && curr->next) {
tmp = curr->next;
curr->next = curr->next->next;
tmp->next = curr;
curr->next = swapPairs(curr->next);
}
return tmp; // don't update head here
}
};
TC -> O(n), n is the length of the linked list
SC -> O(n), n is the length of the linked list (recursive call stack)