function rotateRight<T = number>(
head: ListNode<T> | null,
k: number
): ListNode<T> | null {
// Step 1: エッジケースの処理
if (!head || !head.next || k === 0) {
return head;
}
// Step 2: 長さと末尾を特定
const { length, tail } = findLengthAndTail(head);
// Step 3: 実際の回転数を計算
const actualRotations = k % length;
if (actualRotations === 0) {
return head;
}
// Step 4: 新しい末尾を見つける
const newTail = findNewTail(head, length - actualRotations - 1);
// Step 5: 新しい先頭を設定
const newHead = newTail.next;
// Step 6: ポインタを付け替え
newTail.next = null; // 新しい末尾
tail.next = head; // 循環を作成
return newHead;
}