SDE & MLE Prep

143. Reorder List

Problem

Reorder the list L0→L1→…→Ln in place into L0→Ln→L1→Ln−1→L2→Ln−2→…, relinking nodes rather than changing their values.

Example: 1→2→3→4→5 → 1→5→2→4→3

L0 → Ln → L1 → Ln-1 … = find middle, reverse second half, interleave the halves.

1 2 3 4 5    middle at 3 -> split  1 2 3 | 5 4 (reversed)
merge:       1 5 2 4 3

Complexity: O(n) time, O(1) space.

class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        slow = fast = head
        while fast.next and fast.next.next:
            slow, fast = slow.next, fast.next.next
        prev, cur = None, slow.next
        slow.next = None
        while cur:
            cur.next, prev, cur = prev, cur, cur.next
        a, b = head, prev
        while b:
            an, bn = a.next, b.next
            a.next, b.next = b, an
            a, b = an, bn