forked from BabesGotByte/Coding_SkillSet_Topicwise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnswer33.cpp
41 lines (34 loc) · 897 Bytes
/
Answer33.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
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
//base case
if (head == NULL || head->next == NULL)
return head;
//store k nodes;
ListNode* cur = head;
int c = 0;
//to store kth node
for (int i = 0; i < k && cur != NULL ; i++) {
cur = cur->next;
c++;
}
if (c != k) {
return head;
}
//reverse but only k nodes
ListNode* prev = NULL;
ListNode* t = head;
c = 0;
while (c != k) {
ListNode* nxt = t->next;
t->next = prev;
prev = t;
t = nxt;
c++;
}
//reverse remaining groups and get the head of final linked list
ListNode* rest_h = reverseKGroup(cur, k);
head->next = rest_h;
return prev;
}
};