-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseNodesInKGroup.java
More file actions
52 lines (50 loc) · 1.4 KB
/
ReverseNodesInKGroup.java
File metadata and controls
52 lines (50 loc) · 1.4 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
48
49
50
51
52
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class ReverseNodesInKGroup {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null) return head;
ListNode preHead = new ListNode(0);
ListNode curr = head;
boolean notEnough = false;
ListNode last = preHead;
while(curr!=null) {
int i=0;
ListNode lastCache = null;
while(i<k) {
if(curr!=null) {
if(i==0) lastCache = curr;
ListNode temp = curr.next;
curr.next = last.next;
last.next = curr;
curr = temp;
i++;
} else {
notEnough = true;
break;
}
}
if(!notEnough) {
last = lastCache;
} else {
curr = last.next;
last.next = null;
while(curr!=null) {
ListNode temp = curr.next;
curr.next = last.next;
last.next = curr;
curr = temp;
}
}
}
return preHead.next;
}
}