-
Notifications
You must be signed in to change notification settings - Fork 0
/
25.txt
46 lines (41 loc) · 858 Bytes
/
25.txt
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
Reverse Nodes in K groups
Given a linked list you need to reverse nodes in k groups if number of nodes is less than k, don't reverse
basic reverse is same
ListNode *curr=head,*prev=NULL,*nxt;
while(curr && curr->next){
nxt=curr->next;
curr->next=prev;
prev=curr;
curr=nxt;
}
return prev;
Solution
int get_Length(ListNode *head){
if(!head){
return 0;
}
int len=0;
while(head){
len++;
head=head->next;
}
return len;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *curr=head,*prev=NULL,*nxt;
int len=get_Length(head);
if(len<k || !head){
return head;
}
int n=k;
while(curr && n--){
nxt=curr->next;
curr->next=prev;
prev=curr;
curr=nxt;
}
if(head){
head->next=reverseKGroup(nxt,k);
}
return prev;
}