Hard | LeetCode 25. K 个一组翻转链表 | 反转链表

25. K 个一组翻转链表

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

进阶:

  • 你可以设计一个只使用常数额外空间的算法来解决此问题吗?
  • 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

示例 1:

img
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

示例 2:

img
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]

示例 3:

输入:head = [1,2,3,4,5], k = 1
输出:[1,2,3,4,5]

示例 4:

输入:head = [1], k = 1
输出:[1]

提示:

  • 列表中节点的数量在范围 sz
  • 1 <= sz <= 5000
  • 0 <= Node.val <= 1000
  • 1 <= k <= sz

解题思路

就是反转链表的操作。操作需要小心

public ListNode reverseKGroup(ListNode head, int k) {
    ListNode curHead, curTail = head, cur = head;
    // 新建一个虚拟的哑节点, 统一操作
    ListNode[] preList = new ListNode[]{new ListNode(0), new ListNode(0)};
    ListNode pHead = preList[1];
    while (cur != null) {
        curHead = curTail = cur;
        // 让指针向钱走K步, 记录下一段的起始节点
        boolean lessK = false;
        for (int i = 0; i < k; i++) {
            if (cur == null) {
                lessK = true;
                break;
            }
            curTail = cur;
            cur = cur.next;
        }
        if (lessK) {
            // 如果当前段长度不超过K, 则不反转
            preList[1].next = curHead;
        } else {
            // 如果当前段超过K, 则进行反转
            ListNode[] curList = reverseLinkedList(curHead, curTail);
            // 将前一段尾节点的next指针, 指向当前段的头结点
            preList[1].next = curList[0];
            preList = curList;
        }
    }
    return pHead.next;
}

public ListNode[] reverseLinkedList(ListNode head, ListNode tail) {
    if (head == null) {
        return new ListNode[2];
    }
    ListNode pre = null, cur = head, next = cur.next;
    while (pre != tail) {
        cur.next = pre;
        pre = cur;
        cur = next;
        if (pre != tail) {
            next = cur.next;
        }
    }
    return new ListNode[]{tail, head};
}
原文地址:https://www.cnblogs.com/chenrj97/p/14587557.html