Reorder List

MediumLinked lists

You get the head of a singly linked list whose nodes, in order, are L0, L1, …, Ln. Rearrange its nodes into the order L0, Ln, L1, Ln-1, L2, Ln-2, …: first, last, second, second to last, and so on.

Change the list in place by moving nodes, not by changing their values. The function returns nothing; the test reads the list again from the same head. On this page a list is written as an array of its values, from head to tail.

Examples

Example 1
Input:  head = [10, 20, 30, 40, 50]
Output: [10, 50, 20, 40, 30]

First, last, second, second to last, and the middle node 30 ends the list.

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

4 moves in after 1, and 3 stays after 2.

Constraints

  • The list has 1 to 5 × 10⁴ nodes.
  • -1000 ≤ node.val ≤ 1000

Stuck?

Hint 1

The second half of the list, read backwards, is exactly the order the inserted nodes come in.

Hint 2

Find the middle with a slow and a fast pointer, cut the list there, reverse the second half, then weave the two halves together one node from each.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur