题目
题目链接
题解
/**
* 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 {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode p = head;
ListNode currHead = p;
ListNode prevTail = null;
ListNode resHead = null;
for (int i = 1; p != null; i++, p = p.next) {
if (i % k == 0) {
ListNode nextHead = p.next;
p.next = null;
ListNode[] res = recurrence(currHead);
p = res[1];
p.next = nextHead;
if (prevTail != null) {
prevTail.next = res[0];
}
currHead = nextHead;
prevTail = p;
if (resHead == null) {
resHead = res[0];
}
}
}
return resHead == null ? head : resHead;
}
private ListNode[] recurrence(ListNode node) {
ListNode n = node.next;
if (n == null) {
ListNode[] headAndTail = new ListNode[2];
headAndTail[0] = node;
headAndTail[1] = node;
return headAndTail;
} else {
ListNode[] res = recurrence(n);
n.next = node;
res[1] = node;
return res;
}
}
}