Rotate a Linked List to the Right
Problem statement
Given the head head of a singly linked list and a nonnegative integer k, move the final node to the front k times and return the new head.
A complete rotation preserves order. An empty list returns an empty list. The resulting list must terminate; it must not contain a cycle.
Function
rotateRight(head: ListNode, k: int) → ListNodeExamples
Example 1
head = [1,2,3,4,5]k = 2return = [4,5,1,2,3]The final two nodes become the first two, without reversing them.
Example 2
head = [0,1,2]k = 4return = [2,0,1]Four rightward rotations equal one rotation for a three-node list.
Example 3
head = []k = 7return = []Rotating an empty list leaves it empty.
Constraints
- The list contains
0to500nodes. -100 <= Node.val <= 100.0 <= k <= 2 * 10^9.