Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Reorder a list by alternating ends

Reorder a singly linked list so nodes alternate from the start and end: L0 → Ln → L1 → Ln-1 → ...

Python practice28 minLinked ListsAdvancedLast updated March 27, 2026

Problem statement

Given the head of a singly linked list, reorder the list to follow the pattern: first node, last node, second node, second-last node, and so on. You must modify the list in-place (no new nodes), and return the head of the modified list. If the list is empty or has one node, return it as-is. Hint: A common approach is to find the middle, reverse the second half, then merge the two halves by alternating nodes.

Task

Implement an in-place reordering of a singly linked list by alternating nodes from both ends without creating new nodes.

Examples

Example — even length

Input

[1, 2, 3, 4]

Output

[1, 4, 2, 3]

After reordering: first (1), last (4), second (2), second-last (3).

Input format

A Python list literal is used to construct the linked list via the provided build_list helper (e.g. build_list([1,2,3])).

Output format

Return the head of the reordered list. Tests convert it to a Python list using list_to_py(head).

Constraints

- You must reorder the list in-place (do not allocate new nodes). - Expected time O(n) and O(1) extra space (excluding input conversion helpers). - Number of nodes can be 0 to 10^5 for reasoning, but tests will use modest sizes.

Samples

Sample 1

Input

[1, 2, 3, 4, 5]

Output

[1, 5, 2, 4, 3]

Interleave nodes from the start and end.