-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseNodesKGroup.java
More file actions
45 lines (44 loc) · 1.21 KB
/
Copy pathReverseNodesKGroup.java
File metadata and controls
45 lines (44 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class ReverseNodesKGroup {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode nil = new ListNode(-1);
nil.next = head;
ListNode tmp = head;
ListNode prev = nil;
ListNode next = null;
while(tmp != null){
ListNode last = null;
for(int i = 0; i < k; i++){
if(tmp != null){
next = tmp.next;
tmp.next = last;
last = tmp;
tmp = next;
}else{
for(int j = i; j > 0; j--){
ListNode lastNext = last.next;
last.next = tmp;
tmp = last;
last = lastNext;
}
return nil.next;
}
}
prev.next.next = tmp;
ListNode newPrev = prev.next;
prev.next = last;
prev = newPrev;
}
return nil.next;
}
}