-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverseNodesInKGroup.java
52 lines (44 loc) · 1.3 KB
/
ReverseNodesInKGroup.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
42
43
44
45
46
47
48
49
50
51
52
package com.smlnskgmail.jaman.leetcodejava.hard;
import com.smlnskgmail.jaman.leetcodejava.support.ListNode;
// https://leetcode.com/problems/reverse-nodes-in-k-group/
public class ReverseNodesInKGroup {
private final ListNode head;
private final int k;
public ReverseNodesInKGroup(ListNode head, int k) {
this.head = head;
this.k = k;
}
public ListNode solution() {
return reverse(head, k);
}
private ListNode reverse(ListNode head, int k) {
if (head != null) {
ListNode prev = null;
if (hasNext(head, k)) {
ListNode curr = head;
ListNode next = null;
int count = 0;
while (curr != null && count++ < k) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head.next = reverse(next, k);
} else {
return head;
}
return prev;
}
return null;
}
private boolean hasNext(ListNode head, int k) {
int count = 0;
ListNode p = head;
while (count != k && p != null) {
p = p.next;
count++;
}
return count == k;
}
}