← DSA
MEDIUM

Reorder List

PracticeNeetCode ↗LeetCode ↗

Given the head of a singly linked list, reorder it in place to interleave the first half with the reversed second half: L0 → Ln → L1 → Ln-1 → L2 → … You must do this by rewiring nodes, not by swapping values.

Example

Input head = [1,2,3,4]
Output [1,4,2,3]

Key Pointers

Step-by-Step Analysis

  1. Find the middle of the list with slow/fast pointers.
  2. Split the list at the midpoint and reverse the second half.
  3. Merge the two halves by alternating nodes: one from the first half, one from the reversed second half, repeat.
  4. Set the final node's next to None to terminate the list cleanly.

Complexity

Time: O(n) — Space: O(1)

Code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reorderList(head: ListNode) -> None:
    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    second = slow.next
    slow.next = None
    prev = None
    while second:
        nxt = second.next
        second.next = prev
        prev = second
        second = nxt
    second = prev

    first = head
    while second:
        tmp1, tmp2 = first.next, second.next
        first.next = second
        second.next = tmp1
        first, second = tmp1, tmp2

Code Explanation

How the solution above works, piece by piece.

  1. Phase 1: slow moves 1 step and fast 2 steps; when fast reaches the end, slow is at the middle.
  2. Phase 2: second = slow.next, then slow.next = None splits the list in two. The second half is reversed with the usual prev/curr loop.
  3. Phase 3: weave. Save first.next and second.next in tmp1, tmp2, link first → second → tmp1, then advance both.
  4. The loop runs while second has nodes. The first half is never shorter than the second, so once second runs out, the first half's remaining nodes are already linked in order.
  5. Everything is done by relinking in place: O(n) time, O(1) extra space.

Visual Walkthrough

Running it on head = [1, 2, 3, 4]:

Reorder list in three phases1. slow/fast: fast runs off the end, slow stops at 31234Noneslow2. cut after slow; reverse the second half (just [4] here)123None4Nonesecond3. weave: 1, then 4, then the rest of the first half1423None
The answer takes nodes alternately from the front and the back. Reversing the second half turns "from the back" into a simple forward walk, so the two halves can be merged like a zipper.
first halfsecond half

Video Explanation

NeetCode — LinkedIn Interview Question, LeetCode 143