The second example with k=8 looks incorrect.
Let’s rotate the list for 8 iterations manually:
1 → 2 → 3 → 4 → 5
- 2 → 3 → 4 → 5 → 1
- 3 → 4 → 5 → 1 → 2
- 4 → 5 → 1 → 2 → 3
- 5 → 1 → 2 → 3 → 4
- 1 → 2 → 3 → 4 → 5
- 2 → 3 → 4 → 5 → 1
- 3 → 4 → 5 → 1 → 2
- 4 → 5 → 1 → 2 → 3
So finally we got 4 → 5 → 1 → 2 → 3, not 3 → 4 → 5 → 1 → 2 as the article states.
To achieve that, why can’t we just:
-
Find the tail of the list
-
Move the nodes one by one from the head to the tail of the list, updating the counter?
const rotate = function (head, rotations) {
if (!head || !head.next) return head;let tail = head;
while (tail.next) {
tail = tail.next;
}for (let i = 0; i < rotations; i++) {
tail.next = head;
tail = head;
head = head.next;
tail.next = null;
}return head;
};
Type your question above this line.
Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5497500834201600