Files
2023-07-31 13:57:28 +08:00

1.5 KiB
Raw Permalink Blame History

方法一:快慢指针 + 反转链表 + 合并链表

作者lcbin 链接:https://leetcode.cn/problems/reorder-list/solution/python3javacgo-yi-ti-yi-jie-kuai-man-zhi-t9u2/ 来源力扣LeetCode 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 我们先用快慢指针找到链表的中点,然后将链表的后半部分反转,最后将左右两个链表合并。

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function (head) {
    // 快慢指针找到链表中点
    let slow = head;
    let fast = head;
    while (fast.next && fast.next.next) {
        slow = slow.next;
        fast = fast.next.next;
    }

    // cur 指向右半部分链表
    let cur = slow.next;
    slow.next = null;

    // 反转右半部分链表
    let pre = null;
    while (cur) {
        const t = cur.next;
        cur.next = pre;
        pre = cur;
        cur = t;
    }
    cur = head;

    // 此时 cur, pre 分别指向链表左右两半的第一个节点
    // 合并
    while (pre) {
        const t = pre.next;
        pre.next = cur.next;
        cur.next = pre;
        cur = pre.next;
        pre = t;
    }
};

时间复杂度O(n),其中 n 是链表的长度。空间复杂度O(1)