Fork me on GitHub

Reverse Nodes in k-Group

Description

https://leetcode.com/problems/reverse-nodes-in-k-group/description/

Solution

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) return head;
ListNode new_head = new ListNode(-1);
new_head.next = head;
ListNode traverse = new_head;
while (true) {
if (testReverse(traverse, k) == true) {
traverse = reverseList(traverse, k);
}
else return new_head.next;
}
}

//Return the head tail of partial list
public ListNode reverseList(ListNode start, int k) {
ListNode pre = start.next;
ListNode current = start.next.next;
for (int i = 0; i < k - 1; i++) {
ListNode temp = current.next;
current.next = pre;
pre = current;
current = temp;
}
ListNode originNext = start.next;
start.next = pre;
originNext.next = current;
return originNext;
}

public boolean testReverse(ListNode start, int k) {
while(k > 0) {
if (start.next == null) return false;
k -= 1;
start = start.next;
}
return true;
}
}