-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
37 lines (35 loc) · 816 Bytes
/
Copy pathSolution.java
File metadata and controls
37 lines (35 loc) · 816 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
35
36
37
public class Solution
{
public ListNode reverseKGroup(ListNode head, int k)
{
ListNode ptr = head;
int count = k;
ListNode prev = null;
while (ptr != null && count > 0)
{
prev = ptr;
ptr = ptr.next;
count--;
}
if (count != 0)
{
return head;
}
prev.next = null;
ListNode newHead = reverse(head);
head.next = reverseKGroup(ptr, k);
return newHead;
}
private ListNode reverse(ListNode head)
{
if (head == null || head.next == null)
{
return head;
}
ListNode next = head.next;
head.next = null;
ListNode newHead = reverse(next);
next.next = head;
return newHead;
}
}