Leetcode•May 03, 2025
Rotate List
Hazrat Ali
Leetcode
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]
Solution
/**
* 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}
*/
const rotateRight = (head, k) => {
if (!head) {
return null;
}
const count = getLength(head);
k %= count;
if (k === 0) {
return head;
}
let slow = head;
let fast = head;
while (k-- > 0) {
fast = fast.next;
}
while (fast.next) {
slow = slow.next;
fast = fast.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
};
const getLength = head => {
let count = 0;
while (head) {
head = head.next;
count++;
}
return count;
};