1
class Solution {
2
public ListNode reverseKGroup(ListNode head, int k) {
3
int numOfNodes = count(head);
4
ListNode ptr = null;
5
List<ListNode> start = new ArrayList<>(), end = new ArrayList<>();
6
ListNode f = null;
7
while (head != null) {
8
if (numOfNodes >= k) {
9
start.add(head);
10
int count = 0;
11
while (count < k) {
12
ListNode temp = head.next;
13
head.next = ptr;
14
ptr = head;
15
head = temp;
16
count++;
17
}
18
end.add(ptr);
19
ptr = null;
20
numOfNodes -= count;
21
} else {
22
f = head;
23
break;
24
}
25
}
26
int n = start.size();
27
for (int i = 0; i < n - 1; i++) start.get(i).next = end.get(i + 1);
28
start.get(n - 1).next = f;
29
return end.get(0);
30
}
31

32
public int count(ListNode head) {
33
ListNode temp = head;
34
int count = 0;
35
while (temp != null) {
36
count++;
37
temp = temp.next;
38
}
39
return count;
40
}
41
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0