Skip to content

143. Reorder List

https://leetcode.com/problems/reorder-list/

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function(head) {
    if (!head || !head.next) {
        return head
    }
    const nodes = []
    let current = head
    while (current) {
        nodes.push(current)
        current = current.next
    }

    let i = 0
    let j = nodes.length - 1
    let dummy = new ListNode()
    current = dummy
    while (i < j) {
        current.next = nodes[i]
        nodes[j].next = nodes[i].next
        nodes[i].next = nodes[j]
        current = nodes[j]
        i += 1
        j -= 1
    }
    if (i === j) {
        current.next = nodes[i]
        nodes[i].next = null
    } else {
        current.next = null
    }

    return dummy.next
};