【算法题】链表重排(js)

力扣链接:https://leetcode.cn/problems/LGjMqU/description/
【算法题】链表重排(js)_第1张图片

/**
 * 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.
 */
// 算法:将链表一分为2,将第二段链表反转,然后第一段链表和第二段链表交叉合并
var reorderList = function (head) {
    // 双指针快慢法寻找中间节点
    let slow = head
    let fast = head
    while (fast.next && fast.next.next) {
        slow = slow.next
        fast = fast.next.next
    }
    // 将中间节点的下一节点作为第二段节点的头节点
    let scondList = slow.next
    //断开与第二条链表的链接
    slow.next = null

    // 反转第二条链表
    let pre = null
    let cur = scondList
    while (cur) {
        let temp = cur.next
        cur.next = pre
        pre = cur
        cur = temp
    }
    // 更新第二条链表
    scondList = pre
    //合并链表
    let first = head
    let second = scondList
    while (second) {
        const temp1 = first.next
        const temp2 = second.next
        first.next = second;
        second.next = temp1
        first = temp1
        second = temp2
    }
};

你可能感兴趣的:(算法题,算法,链表,javascript)