forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcodeReverseNodesInKGroup.java
More file actions
49 lines (41 loc) · 1.17 KB
/
LeetcodeReverseNodesInKGroup.java
File metadata and controls
49 lines (41 loc) · 1.17 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
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(k<=1 || head == null) return head;
ListNode current = head;
ListNode prev = null;
ListNode temp = head;
int count = 0;
while(temp != null){
count++;
temp = temp.next;
}
int run = count/k;
while(true){
if(run==0) break;
ListNode last = prev;
ListNode newEnd = current;
ListNode next = current.next;
for(int i=0; current != null && i<k;i++){
current.next = prev;
prev = current;
current = next;
if(next != null){
next = next.next;
}
}
if(last != null){
last.next = prev;
}
else{
head = prev;
}
newEnd.next = current;
if(current == null ){
break;
}
prev = newEnd;
run--;
}
return head;
}
}