
Leetcode Problem 61: Rotate List
Given the head of a linked list and an integer k, rotate the list to the right by k positions — the last k elements are moved to the front of the list, preserving their relative order.
Constraints:
k is a non-negative integer up to 2,000,000,000.import { ListNode } from "../list-node"
function rotateRight(head: ListNode | null, k: number): ListNode | null {
if (!head || k === 0) {
return head
}
let dummy = new ListNode(-1, head)
let slow: ListNode | null = dummy
let fast: ListNode | null = dummy
let current: ListNode | null = head
let total = 0
while (current) {
current = current.next
total++
}
let rotation = Math.floor(k % total)
if (rotation === 0) {
return head
}
for (let i = 0; i < rotation; i++) {
fast = fast!.next
}
while (fast?.next) {
slow = slow!.next
fast = fast.next
}
let newHead = slow!.next
slow!.next = null
fast!.next = head
head = newHead
return head
};