forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.java
35 lines (34 loc) · 936 Bytes
/
Solution2.java
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (k == 1) return head;
ListNode res = new ListNode(0);
ListNode slow = head, fast = head, index = res;
int i = 1;
while (fast != null) {
ListNode temp = fast.next;
if (i ++ % k == 0) {
fast.next = null;
ListNode zou = slow;
while (slow != null) {
ListNode itme = slow.next;
slow.next = index.next;
index.next = slow;
slow = itme;
}
index = zou;
slow = temp;
}
fast = temp;
}
index.next = slow;
return res.next;
}
}