Skip to content
StackDecode
Linked listsAnimated

Rotate Linked List

Connect the tail to the head and cut at the new tail.

Time

O(n)

Extra space

O(1)

Use it for

Rotating by k positions.

How it works

  1. Rotating right by k moves the last k nodes to the front.
  2. Find the length n and use k mod n (rotating by n changes nothing).
  3. Connect the tail to the head to form a ring.
  4. Walk n − k steps to the new tail, and cut the ring after it. The next node is the new head.

Watch it run

Loading animation…