Rotate List
Given the head of a singly linked list, rotate the list to the right by k places.
A right rotation by one place moves the last node of the list to the front. Return the new head of the rotated list.
If the list is empty, has one node, or k is effectively 0 after accounting for the list length, return the appropriate head without changing the list structure unnecessarily.
Example 1
[1] -> [2] -> [3] -> [4] -> [5] -> null --- [4] -> [5] -> [1] -> [2] -> [3] -> null
Input
head = [1,2,3,4,5], k = 2Output
[4,5,1,2,3]Rotating the list right by 2 moves 4 and 5 to the front, producing 4 -> 5 -> 1 -> 2 -> 3.
Example 2
[0] -> [1] -> [2] -> null --- [2] -> [0] -> [1] -> null
Input
head = [0,1,2], k = 4Output
[2,0,1]Rotating right by 4 is equivalent to rotating right by 1 for a list of length 3, producing 2 -> 0 -> 1.
Constraints
- 0 <= number of nodes in the list <= 500
- -100 <= Node.val <= 100
- 0 <= k <= 2 * 10^9