Task example: Reorder List

Rearrange a singly linked list by taking its first node, then its last node, then its second node, then its second-to-last node, and so on. Change next links in place. Keep each node and its value.

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

Output shows the list after reordering. The function returns None, not a new list. The task allows 1 to 50,000 nodes with values from 1 to 1000.

LeetCode 143 ↗
01 / Node-reference list

Node-reference list: video explanation

head = [1,2,3,4,5]
output: [1,5,2,4,3]

Prefer reading? Follow the steps below.

  1. Walk through the list and store references to its nodes. Do not store only their values: we must reconnect the original nodes.
  2. Use left and right indices. Link the left node to the right node, move left inward, then link the right node to the new left node and move right inward. Stop if the indices meet.
  3. Set the final node's next link to None. Without this step, an old link can create a cycle. The function finishes without returning a list.

Time complexity · O(N)

Collecting and reconnecting the N nodes takes linear time.

Space complexity · O(N)

The extra list stores N node references.

PYTHONLive code trace
02 / Split, reverse & weave

Split, reverse & weave: optimal-space video explanation

head = [1,2,3,4,5]
output: [1,5,2,4,3]

Prefer reading? Follow the steps below.

  1. Move slow by one link and fast by two until slow is at the end of the first half. Save slow.next, then set slow.next to None to separate the halves.
  2. Reverse the second half using prev, second, and following. Save the next link before reversing it, so the remaining nodes are not lost.
  3. Weave the halves together. Save both next links, connect first to second and second to the saved next_first, then advance. Stop when the second half is exhausted; an extra middle node stays at the end.

Both approaches take O(N) time. Splitting, reversing, and weaving avoids the extra reference list and reduces space complexity from O(N) to O(1).

Time complexity · O(N)

Finding the middle, reversing half the list, and weaving the halves each take linear time. Their total is O(N).

Space complexity · O(1)

Only a fixed number of node references is used. The reversal is iterative, with no recursion stack.

PYTHONLive code trace

Reorder List · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.