思路: 先写反转 [head, tail)
的函数, 随后主函数先反转前 K 个链表, 再将该链表的头节点 (反转之后变成了尾节点) 的 next 设置为递归的返回值 (新的头节点)
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode tail = head;
for (int i = 0; i < k; i++) {
if (tail == null) return head;
tail = tail.next;
}
// [head, tail)
ListNode newHead = reverse(head, tail);
head.next = reverseKGroup(tail, k);
return newHead;
}
private ListNode reverse(ListNode head, ListNode tail) {
ListNode pre = null, curr = head, nxt = head;
while (curr != tail) {
nxt = nxt.next;
curr.next = pre;
pre = curr;
curr = nxt;
}
return pre;
}
}