-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_25.java
More file actions
34 lines (30 loc) · 924 Bytes
/
Copy pathP_25.java
File metadata and controls
34 lines (30 loc) · 924 Bytes
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
package leetcode.hard;
import utils.DataStructures.ListNode;
public class P_25 {
public ListNode reverseKGroup(ListNode head, int k) {
final ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode iter = dummy;
for (int i = 0; i < k && iter != null; i++) {
iter = iter.next;
}
if (iter == null) {
return head;
}
final ListNode next = iter.next;
//noinspection ConstantConditions
iter.next = null;
final ListNode rev = reverse(head, null);
head.next = reverseKGroup(next, k);
return rev;
}
private static ListNode reverse(ListNode curr, ListNode newHead) {
if (curr == null) {
return newHead;
}
final ListNode temp = curr.next;
curr.next = newHead;
//noinspection TailRecursion
return reverse(temp, curr);
}
}