Skip to interview prep
Apexed

85. Reorder a List (First, Last, Second, …)

MediumLinked lists

Given a list L0 → L1 → … → Ln, reorder its nodes to L0 → Ln → L1 → Ln−1 → L2 → … and return the head. Relink the existing nodes; do not change their values.

A linked list is passed as ListNode objects with val and next. The tests write lists as arrays.

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]

Constraints

  • 0 ≤ nodes ≤ 5 · 10⁴

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 5 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Reorder a List (First, Last, Second, …) — coding interview practice — Apexed