Blind 75 · Linked List

Reorder List

Medium

Watch the walkthrough (5:39)

Problem

The input is head, the first node of a linked list.
Reorder the list: the first node, the last, the second, the second to last, and so on.
Change only each node's next; never copy or change a val.
Return nothing: the list is reordered in place, from head.

Examples

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

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

Example 3:
Input: head = [1]
Output: [1]

Example 4:
Input: head = [1,2]
Output: [1,2]

Constraints

1 <= list length <= 5 * 10^4
1 <= Node.val <= 1000

Prerequisites

Linked lists — a node holds a value and a next reference, and rearranging a list means moving references, never values.
Dummy heads: a node in front of the list so the first element stops being a special case.
Two pointers on a list — one ahead of the other, or one moving twice as fast.

How to think about it

1. Split, Reverse, Weave Optimal

Intuition

The target order takes from the front and the back alternately, and a singly linked list cannot walk backwards — so make the back half walk forwards instead by reversing it. Three techniques in sequence, which is why this problem gets asked: find the middle with slow and fast pointers, reverse the second half, then interleave. Cutting the first half's tail before weaving is the step everyone forgets, and without it the two halves stay joined and the weave loops.

Algorithm

1. Find the middle with slow and fast pointers.
2. Cut there, so the first half ends cleanly.
3. Reverse the second half.
4. Weave the two halves, taking one node from each in turn.

Time & Space

Time O(n). Space O(1).

2. Every Node in an Array, Relinked from Both Ends

Intuition

An array can be read from both ends, where a singly linked list cannot. Put every node in an array in list order, and walk two indexes inward, i from the front and j from the back: node i points at node j, then node j at the node after i, until the two indexes meet. The node they meet on is the last of the new order, so its next is set to null, and the list ends there. Only next is changed and no val is copied; what it costs is the array.

Algorithm

1. Walk from the head, putting each node in an array.
2. Start i at the first index and j at the last.
3. While i is before j, point node i at node j and step i forward; stop if i has reached j, or else point node j at node i and step j back.
4. Point the node at i, where the two indexes met, at null.

Time & Space

Time O(n). Space O(n): the array holds every node, which Split, Reverse, Weave does without.