-
Notifications
You must be signed in to change notification settings - Fork 168
/
reverse_groups_k.cpp
82 lines (76 loc) · 2.13 KB
/
reverse_groups_k.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
/*
Problem Link: https://leetcode.com/problems/reverse-nodes-in-k-group/
*/
/**
* 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 {
// temp head and tail
ListNode *th = NULL, *tt = NULL;
public:
// helper function to calculate the size of the linked list
int length(ListNode *head) {
int size = 0;
while(head) {
size++;
head = head->next;
}
return size;
}
// helper function to add node at the starting of the list
void addFirst(ListNode *node) {
if(th == NULL)
th = tt = node;
else {
node->next = th;
th = node;
}
}
ListNode* reverseKGroup(ListNode* head, int k) {
// edge cases
if(!head || !head->next || k == 1)
return head;
// find the length of the list
int size = length(head);
ListNode *curr = head;
// original head and tails for the final merged linked list
ListNode *oh = NULL, *ot = NULL;
while(size >= k) {
int temp = k;
// reverse the links of K nodes
while(temp--) {
// take the left most node
ListNode *N = curr->next;
// break the link
curr->next = NULL;
addFirst(curr);
// update values for next iteration
curr = N;
}
// first set of k reversed nodes
if(!oh) {
oh = th;
ot = tt;
}
else {
ot->next = th;
ot = tt;
}
// reset th and tt
th = tt = NULL;
// decrease size
size -= k;
}
// attach the remaining part: residual group of size < k
if(size)
ot->next = curr;
return oh;
}
};