CodingNodes / Linked List / Reorder List System design Space play · ←→ step · R restart

Problem

You are given the head of a singly linked list L0 → L1 → … → Ln-1 → Ln. Rearrange it in place into L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …: first node, last node, second node, second-to-last node, and so on.

Do not change any node's value, only the arrows between nodes. The function returns nothing; the list starting at head is the answer.

Constraints

  • 1 ≤ number of nodes ≤ 50000
  • 1 ≤ Node.val ≤ 1000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: Finding the middle, reversing the back half and weaving the two halves each touch every node a constant number of times.

Space: All the work is pointer changes on the existing nodes. No array or extra list is built.

The new order takes nodes alternately from the front and from the back. Reversing the second half puts the back nodes in the order we need them. So: find the middle with slow and fast, cut the list there, reverse the second half, then interleave the two lists one node at a time.