-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path25.cpp
More file actions
47 lines (46 loc) · 1.21 KB
/
Copy path25.cpp
File metadata and controls
47 lines (46 loc) · 1.21 KB
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
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (!head || !head->next)
return head;
ListNode *temp = head, *start = new ListNode(0), *ret = start;
start->next = head;
int n = 0, left = 0;
while (temp) {
temp = temp->next;
++n;
}
left = n % k;
n /= k;
while (n > 0) {
ListNode *update = nullptr;
if (left != 0 || n > 1) {
ListNode *t = head;
int m = k;
while (m > 0) {
--m;
t = t->next;
}
update = t;
}
ListNode *tail = reverseListNode(head, k);
start->next = tail;
start = head;
head = update;
--n;
}
start->next = head;
return ret->next;
}
ListNode *reverseListNode(ListNode *head, int k) {
ListNode *temp = head, *prev = nullptr, *next = nullptr;
while (k > 0) {
next = temp->next;
temp->next = prev;
prev = temp;
temp = next;
--k;
}
return prev;
}
};