Given the head of a linked list, rotate the list to the right by k places.

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Input: head = [0,1,2], k = 4
Output: [2,0,1]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or not head.next or k == 0:
return head
# 1. μ 체 λ
Έλ μ μΉ΄μ΄νΈ
length = 1
current = head
while current.next:
current = current.next
length += 1
# 2. νμ νμ μ‘°μ
k = k % length
if k == 0:
return head
# 3. 리μ€νΈ λκ³Ό μμ μ°κ²°
current.next = head
# 4. μλ‘μ΄ ν€λλ₯Ό μ°ΎκΈ° μν΄ λΆλ¦¬ μ§μ μ κ²°μ
steps_to_new_head = length - k
new_tail = head
for _ in range(steps_to_new_head - 1):
new_tail = new_tail.next
# 5. μλ‘μ΄ ν€λ μ€μ λ° λ¦¬μ€νΈ λΆλ¦¬
new_head = new_tail.next
new_tail.next = None
return new_head
