forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Nodes in k-Group.java
41 lines (41 loc) · 1.17 KB
/
Reverse Nodes in k-Group.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
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
int numOfNodes = count(head);
ListNode ptr = null;
List<ListNode> start = new ArrayList<>(), end = new ArrayList<>();
ListNode f = null;
while (head != null) {
if (numOfNodes >= k) {
start.add(head);
int count = 0;
while (count < k) {
ListNode temp = head.next;
head.next = ptr;
ptr = head;
head = temp;
count++;
}
end.add(ptr);
ptr = null;
numOfNodes -= count;
}
else {
f = head;
break;
}
}
int n = start.size();
for (int i = 0; i < n - 1; i++) start.get(i).next = end.get(i + 1);
start.get(n - 1).next = f;
return end.get(0);
}
public int count(ListNode head) {
ListNode temp = head;
int count = 0;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
}