KatInterview

Reorder Linked List Nodes by Alternating Ends

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked liststwo pointersarray manipulation

Last updated

Tests pointer-manipulation intuition by reordering a singly linked list (given as an array) in a front-back-front-back zigzag pattern.

Reorder Linked List Nodes by Alternating Ends

You are given a singly linked list represented as a plain Python list of integers nodes. The list has n nodes with values nodes[0], nodes[1], ..., nodes[n-1].

Your task is to reorder the list in the following pattern:

nodes[0] → nodes[n-1] → nodes[1] → nodes[n-2] → nodes[2] → nodes[n-3] → ...

That is, repeatedly pick from the front, then from the back, alternating, until all nodes have been placed.

Return the reordered list of values as a Python list.

Do not sort the values. You are only rearranging the existing nodes.

How the reordering works

Use two pointers — one starting at the front (lo = 0) and one at the back (hi = n-1). At each step:

  1. Take the element at lo, advance lo forward.
  2. If lo <= hi after step 1, take the element at hi, move hi backward.

Repeat until all elements are consumed.

Constraints

  • 0 <= n <= 2000
  • -10^6 <= nodes[i] <= 10^6
  • If n == 0, return [].
  • If n == 1, return the single-element list unchanged.

Examples

Example 1

Input: reorder_linked_list([1, 2, 3, 4, 5])

Output: [1, 5, 2, 4, 3]

Example 2

Input: reorder_linked_list([10, 20, 30, 40])

Output: [10, 40, 20, 30]

Example 3

Input: reorder_linked_list([7])

Output: [7]

Hints

Hint 1

Try using two index pointers — one at the start and one at the end of the list — and advance them inward while alternating which one you pull from.

Hint 2

Think about what happens when the list has an odd length versus an even length. The middle element (if it exists) will be picked last from the 'front' pointer, with no back-pointer element to pair it with.

Hint 3

You can simulate this without any actual linked list nodes: just build the result list by appending from lo, then from hi, advancing each pointer inward by one each round.