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
- Rotating right by k moves the last k nodes to the front.
- Find the length n and use k mod n (rotating by n changes nothing).
- Connect the tail to the head to form a ring.
- 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…