-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathReverse-Nodes-in-k-Group.cpp
40 lines (36 loc) · 1.04 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
/**
* 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(k==0) return head;
ListNode *temp=head; //to ensure there are k nodes present in LL to reverse, else return head
for(int i=0;i<k;i++){
if(temp==NULL) return head;
temp=temp->next;
}
ListNode* prevptr=NULL;
ListNode* curptr=head;
ListNode* nextptr;
int count=0;
while(curptr!=NULL && count<k){
nextptr=curptr->next;
curptr->next=prevptr;
prevptr=curptr;
curptr=nextptr;
count++;
}
if(nextptr!=NULL){
head->next=reverseKGroup(nextptr,k);
}
return prevptr;
}
};