-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question48.cpp
41 lines (40 loc) · 948 Bytes
/
Question48.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
48 -> Reverse Nodes in K Groups
Solution :
class Solution {
public:
int getlength( ListNode* head){
ListNode*temp=head;
int count=0;
while(temp!=NULL){
temp=temp->next;
count++;
}
return count;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if(head==NULL||head->next==NULL){
return head;
}
ListNode*curr=head;
ListNode*prev=NULL;
ListNode*forward=NULL;
int count=0;
while(curr!=NULL&&count<k){
forward=curr->next;
curr->next=prev;
prev=curr;
curr=forward;
count++;
}
int len=getlength(curr);
if(len>=k){
if(curr!=NULL){
head->next=reverseKGroup(curr,k);
}
}
else{
head->next=curr;
}
return prev;
}
};