Rotate List Visualizer & Step-by-Step Algorithm Solution

Rotate the linked list to the right by k places by connecting the tail to head and severing at (length - k % length).

Category: linked-list | Difficulty: Medium

Tags: Linked List, Two Pointers, Circular List

Rotate List

head
1
2
3
4
5
100%
state
k2
length5
Initialization
1/14
Explanation

Start rotateRight with k = 2.

Source Code
1function rotateRight(head, k) {
2 if (!head || !head.next || k === 0) return head;
3 let length = 1, tail = head;
4 while (tail.next) {
5 tail = tail.next;
6 length++;
7 }
8 k = k % length;
9 if (k === 0) return head;
10 tail.next = head;
11 let stepsToNewTail = length - k, newTail = head;
12 for (let i = 1; i < stepsToNewTail; i++) {
13 newTail = newTail.next;
14 }
15 const newHead = newTail.next;
16 newTail.next = null;
17 return newHead;
18}