Visualize

Pattern visualizer

Rotate List

Rotating right by k moves the last k nodes to the front. Doing that one node at a time costs a full scan per rotation, and k can be far larger than the list. Instead, walk once to the last node while counting the length n, then link that last node back to the head. The list is now a ring, and every rotation of a ring is the same ring — only the place it is cut open differs. Reduce k to k MOD n, walk n - k - 1 steps from the head to the new tail, take its next as the new head, and break the ring there. Two partial passes, constant extra space, and k's size never matters. Animated on: list = [1,2,3,4,5], k=2. Rotate the list to the right by k places. Answer: [4,5,1,2,3]..

Close the list into a ring, then cut it at n - k MOD n

time O(n)space O(1)step 1 / 12
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
line 3

list = [1,2,3,4,5], k=2. A singly-linked list has no length field, so the first job is to walk to the last node and count on the way: n <- 1 at the head. The last node is needed anyway, because rotation reconnects it to the head.

Pseudocode
1FUNCTION rotateRight(head, k)
2 IF head = NULL RETURN head
3 n <- 1, tail <- head
4 WHILE tail.next != NULL
5 tail <- tail.next
6 n <- n + 1
7 k <- k MOD n
8 IF k = 0 RETURN head
9 tail.next <- head
10 newTail <- head
11 FOR i <- 1 TO n - k - 1
12 newTail <- newTail.next
13 head <- newTail.next
14 newTail.next <- NULL
15 RETURN head

← / → step · space play · Home restart

Where to practice Linked List