Linked List - Neetcode

Remove nth node from end:

Reorder list


var reorderList = function (head) {
    if (!head || !head.next) return head;

    // Step 1: Find the middle of the list for second half
    let slow = head, fast = head.next;
    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }

    // Step 2: Reverse the second half from 'slow'
    let prev = null, curr = slow;
    while (curr) [curr.next, prev, curr] = [prev, curr, curr.next];

	//Step 3: build connection - merge
    let first = head;
    let second = prev;
    while (first) { //first is longer than second always
        const tmp1 = first.next;
        const tmp2 = second.next;
        first.next = second;
        second.next = tmp1;
        first = tmp1;
        second = tmp2;
    }
};