-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
43 lines (38 loc) · 925 Bytes
/
Solution.java
File metadata and controls
43 lines (38 loc) · 925 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
38
39
40
41
42
43
package leetCode_25;
/**
* @author dimdark
* @date 2017-10-08
* @time 9:58 PM
*/
public class Solution {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
this.val = x;
}
}
private ListNode reverse(ListNode first, ListNode last) {
ListNode prev = last;
while (first != last) {
ListNode temp = first.next;
first.next = prev;
prev = first;
first = temp;
}
return prev;
}
public ListNode reverseKGroup(ListNode head, int k) {
if (k <= 0) return head;
ListNode node = head;
for (int i = 0; i < k; ++i) {
if (node == null) {
return head;
}
node = node.next;
}
ListNode newHead = reverse(head, node);
head.next = reverseKGroup(node, k);
return newHead;
}
}