- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathReverseNodesInKGroup.java
52 lines (46 loc) · 1.38 KB
/
ReverseNodesInKGroup.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// https://leetcode.com/problems/reverse-nodes-in-k-group/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
classSolution {
publicListNodereverseKGroup(ListNodehead, intk) {
if (k == 1) returnhead;
ListNodeslow = head, fast = head, newHead = head;
ListNodeprev = null, next = head;
intcount = 0;
booleanisStart = true;
while (fast != null) {
count++;
if (count != k) fast = fast.next;
else {
if (!isStart) {
next = slow.next;
slow.next = fast;
slow = next;
} else {
isStart = false;
newHead = fast;
}
prev = fast.next;
ListNodetempFast = fast.next, tempSlow = slow;
while (count > 0) {
count--;
next = slow.next;
slow.next = prev;
prev = slow;
slow = next;
}
slow = tempSlow;
fast = tempFast;
}
}
returnnewHead;
}
}