-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp025.c
47 lines (47 loc) · 1.39 KB
/
p025.c
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
if (head == NULL || k == 1) return head;
int cnt = 0;
struct ListNode *prevtail = NULL, *curtail = head, *oldhead = head, *newhead = head->next;
struct ListNode *result = head, *memoldhead = oldhead, *curtailnext = curtail->next;
while (true)
{
if (curtail != NULL)
{
cnt++;
if (cnt == k)
{
memoldhead = oldhead;
curtailnext = curtail->next;
while (oldhead != curtail)
{
if (prevtail != NULL) prevtail->next = newhead;
oldhead->next = curtail->next;
curtail->next = oldhead;
oldhead = newhead;
newhead = newhead->next;
}
if (result == head) result = curtail;
prevtail = memoldhead;
curtail = oldhead = curtailnext;
if (oldhead != NULL) newhead = oldhead->next;
cnt = 0;
}
else
{
curtail = curtail->next;
}
}
else
{
break;
}
}
return result;
}