-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse_nodes_in_k_group.cpp
48 lines (43 loc) · 1.19 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
// 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 {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(head==NULL || k==1) return head;
ListNode *dummy = new ListNode(0);
dummy->next=head;
ListNode *curr=dummy, *prev=dummy, *nex=dummy;
//For counting
int count=0;
while(curr->next!=NULL)
{
curr=curr->next;
count++;
}
// For main implementation
while(count>=k)
{
curr=prev->next;
nex=curr->next;
for(int i=1;i<k;i++)
{
curr->next=nex->next;
nex->next=prev->next;
prev->next=nex;
nex=curr->next;
}
prev=curr;
count-=k;
}
return dummy->next;
}
};