25. K 个一组翻转链表
递归
辅助函数 reverse 用于翻转 [head, tail),返回翻转后的头节点
总体思路:
1、找到待翻转的前 k 个节点,如果链表长度小于 k 则无需翻转
2、将其翻转,注意是左闭右开的,这里用到了辅助函数 reverse
3、对下一轮 k 个节点也进行翻转操作
4、将上一轮翻转后的尾节点指向下一轮翻转后的头节点
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:38.6 MB, 在所有 Java 提交中击败了70.72%的用户
public class Solution {public ListNode reverseKGroup(ListNode head, int k) {if (head == null || head.next == null) {return head;}ListNode tail = head;for (int i = 0; i < k; i++) {// 如果长度小于 k 则不需要翻转if (tail == null) {return head;}tail = tail.next;}// 翻转 [head, tail),返回翻转后的头节点ListNode newHead = reverse(head, tail);// 将本轮翻转的尾节点指向下一轮翻转的头节点,递归调用head.next = reverseKGroup(tail, k);return newHead;}// 左闭右开区间的翻转public ListNode reverse(ListNode head, ListNode tail) {ListNode pre = null;ListNode next = null;while (head != tail) {next = head.next;head.next = pre;pre = head;head = next;}return pre;}}

