-
Notifications
You must be signed in to change notification settings - Fork 142
/
Reverse Nodes in k-Group.cpp
67 lines (62 loc) · 1.74 KB
/
Reverse Nodes in k-Group.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
// Recursive approach Space O(N) (Stack)
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
int size = 0;
ListNode *temp = head;
while(temp!=NULL){
temp = temp -> next;
size++;
}
if(size < k) return head;
// Base call
if(head == NULL)
return NULL;
// Step 1 - Reverse first k nodes
ListNode *curr = head, *prev = NULL, *next = NULL;
int count = 0;
while(curr != NULL && count <k){
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
count++;
}
// Step 2 - Use recursion to reverse rest of the nodes
if(next!=NULL){
head->next = reverseKGroup(next, k);
}
// Step 3 - Return head
return prev;
}
};
// Iterative approach Space - O(1)
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *before = dummy, *after = head;
ListNode *curr = NULL, *prev = NULL, *nxt = NULL;
while(true){
ListNode* cursor = after;
for(int i = 0; i < k; i++){
if(cursor == nullptr)
return dummy->next;
cursor = cursor->next;
}
curr = after;
prev = before;
for(int i = 0; i < k; i++){
nxt = curr->next;
curr->next = prev;
prev = curr;
curr = nxt;
}
after->next = curr;
before->next = prev;
before = after;
after = curr;
}
}
};