Description
Given the head of a linked list, rotate the list to the right by k places.
Example 1:
Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4 Output: [2,0,1]
Constraints:
- The number of nodes in the list is in the range
[0, 500]. -100 <= Node.val <= 1000 <= k <= 2 * 109
Solutions
This takes a fundamentally different approach by eliminating the dummy node entirely. It counts the list while tracking the tail node, calculates effective rotation, then traverses to find the new tail position. It directly disconnects at the new tail and reconnects the old tail to the original head, returning the new head without helper structures.
Language: javascript(2026-05-05 09:15)DONE
CPU Performance100.00%
Memory Performance50.44%
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function(head, k) {
if (!head) return null;
if (k === 0) return head;
let node = head;
let prev = null;
let count = 0;
while (node) {
prev = node;
node = node.next;
count++;
}
k %= count;
if (k === 0) return head;
let tail = prev;
let flips = count - k;
node = head;
prev = null;
while (flips > 0) {
prev = node;
node = node.next;
flips--;
}
if (prev) prev.next = null;
if (tail) tail.next = head;
return node;
};