-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
38 lines (38 loc) · 968 Bytes
/
solution.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *reverseKGroup(ListNode *head, int k)
{
if( head==NULL || k==1 )
return head;
int sum=0;
ListNode *preheader = new ListNode(0);
preheader->next = head;
ListNode *current = preheader, *forward, *precede = preheader;
while(current = current->next)
sum++;
while(sum>=k)
{
current = precede->next;
forward = current->next;
for(int i=1;i<k;++i)
{
current->next=forward->next;
forward->next=precede->next;
precede->next=forward;
forward=current->next;
}
precede = current;
sum-=k;
}
return preheader->next;
}
};