思路
似乎是个经典题目
思路就是一个递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
private ListNode reverse(ListNode a, ListNode b){
ListNode cur = a;
ListNode prev = null;
ListNode nextt = a;
while(cur != b){
nextt = cur.next;
cur.next = prev;
prev = cur;
cur = nextt;
}
return prev;
}
public ListNode reverseKGroup(ListNode head, int k) {
ListNode a = head;
ListNode b = head;
for(int i = 0; i < k; i++){
if(b == null)
return head;
b = b.next;
}
ListNode newHead = reverse(a, b);
//连接起来
a.next = reverseKGroup(b, k);
return newHead;
}
}