InterviewPrepKit

Home / Coding / Linked List

Reorder List

medium Original β†—
Solving tips
  • Recognize the target as the first half interleaved with the reversed second half, and solve it by composing three classic routines.
  • Chain: (1) find the middle with slow/fast pointers, (2) reverse the second half in place, (3) merge the two halves alternately.
  • Set slow.next = None to cut the list before reversing, or the merge will loop forever or duplicate nodes.
  • Target O(n) time and O(1) space; relink nodes rather than rewriting values, and prefer iteration over recursion at 5e4 nodes.

Problem

Given the head of a singly linked list L0 β†’ L1 β†’ … β†’ L(n-1), rearrange its nodes in place into the interleaved order:

L0 β†’ L(n-1) β†’ L1 β†’ L(n-2) β†’ L2 β†’ L(n-3) β†’ …

That is, alternate between the front of the list and the back of the list, working inward. Only node links may be changed β€” you may not rewrite node values. The function returns nothing; it mutates the list.

Examples

  • Input: head = [1, 2, 3, 4] β†’ List becomes [1, 4, 2, 3] Front 1, back 4, front 2, back 3.
  • Input: head = [1, 2, 3, 4, 5] β†’ List becomes [1, 5, 2, 4, 3] Front 1, back 5, front 2, back 4, and the middle 3 lands last.
  • Input: head = [7, 9] β†’ List becomes [7, 9] Two nodes are already in reordered form.

Constraints

  • 1 <= n <= 5 * 10^4 where n is the number of nodes.
  • 1 <= Node.val <= 1000.

At 5Β·10^4 nodes, repeatedly walking to the current tail (O(nΒ²)) is on the edge; the intended solution is O(n) time, and the classic follow-up is O(1) extra space.

Think about it first

Hint 1 The output alternates between two sequences: the first half in order, and the second half in reverse. Can you produce those two sequences?
Hint 2 With all nodes in an array, two indices (one at each end, moving inward) can relink everything. That costs O(n) space β€” what linked-list tools give you "second half, reversed" without an array?
Hint 3 Three classics chained together: (1) slow/fast pointers to find the middle, (2) reverse the second half in place, (3) merge the two halves alternately. Each step is a well-known routine; the problem is just their composition.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.