-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path25-kreverselist!!!.java
More file actions
36 lines (36 loc) · 929 Bytes
/
25-kreverselist!!!.java
File metadata and controls
36 lines (36 loc) · 929 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution_25 {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || k==0) return head;
ListNode pre = null;
int count = 0, cur = 0;
ListNode check = head, res = head, next = null;
while(cur < k && check != null) {
check = check.next;
cur ++;
}
if(cur == k) {
while(count < k && res != null) {
next = res.next;
res.next = pre;
pre = res;
res = next;
count ++;
}
if(next != null) {
head.next = reverseKGroup(next, k);
}
return pre;
} else {
// 不够k
return head;
}
}
}