LeetCode热题(JS版)- 143. 重排链表

22 阅读1分钟

题目

给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln 请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … 不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

image.png

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

示例 2:

image.png

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

提示:

链表的长度范围为 [1, 5 * 104]
1 <= node.val <= 1000

思路

这道题可以使用快慢指针的方法,首先使用快慢指针法找到链表的中间节点,然后将链表分成两个部分,将后面一半链表翻转,最后再将两个链表合并。 具体来说,我们可以使用快慢指针法找到链表的中间节点,然后将链表分成两个部分,然后将后面一半链表翻转,最后再将两个链表合并。

  • 时间复杂度为O(n)
  • 空间复杂度为O(1)
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

/**
 Do not return anything, modify head in-place instead.
 */
function reorderList(head: ListNode | null): void {
    if(!head || !head.next) return null;

    // 快慢指针找到中间元素
    let slow = head, fast = head;
    while(fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }

    // 链表断开为两个部分
    const h1 = head;
    let h2 = slow.next;
    slow.next = null;

    // 翻转后面一部分
    let pre = null;
    let curr = h2;
    while(curr) {
        const next = curr.next;// pre -> curr -> next

        curr.next = pre;// curr -> pre 翻转

        pre = curr;// pre后移

        curr = next;// curr后移
    }
    h2 = pre;// 最后一个到最前面了

    // 合并链表。三条链表,交替接续,再依次后移
    let dummy = new ListNode();
    let h = dummy;
    let cur1 = h1;
    let cur2 = h2;
    while(cur1 && cur2) {
        h.next = cur1; cur1 = cur1.next; h = h.next
        h.next = cur2; cur2 = cur2.next; h = h.next
    }
    if(cur1) h.next = cur1;
    if(cur2) h.next = cur2;

    head = dummy.next;
};

image.png