forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.h
29 lines (25 loc) · 784 Bytes
/
solution.h
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
#include <cstddef>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (!head || !head->next || k<2) return head;
ListNode pre(0);
pre.next = head;
for (ListNode *front = &pre, *back = ⪯ true; front = head, back = head) {
for (int count = k; count > 0; --count)
if (!(back = back->next)) return pre.next;
for (head = front->next; front->next != back; ) {
ListNode *next = front->next;
front->next = next->next;
next->next = back->next;
back->next = next;
}
}
return pre.next;
}
};