Practice · Linked list · 5 of 6

Interleave a Linked List from Both Ends

You are given head, the first node of a singly linked list.

Rearrange the nodes in place so they come in the order first, last, second, second to last, third, third to last, and so on: the list A → B → C → D → E becomes A → E → B → D → C. Change the next pointers only, not the values, and return nothing; the answer is read from head.

Linked lists are written as their values from head to tail, so [1, 4, 6] is 1 → 4 → 6.

Example 1

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

Example 2

Input
head = [10, 20, 30, 40, 50]
Output
[10, 50, 20, 40, 30]
With an odd number of nodes, the middle one ends up last.

Constraints

  • The list holds 1 to 5000 nodes.
  • Every value is between 1 and 1000.