You get the head of a singly linked list and a number k. Rotate the list k places to the right: one rotation takes the last node off the end and puts it at the front. Return the head of the list after k rotations.
k can be far larger than the length of the list.
The first rotation brings 6 to the front, and the second brings 4 in front of it.
Three rotations bring a 3-node list back to where it started, so seven rotations land in the same place as one.
An empty list has nothing to rotate: return null.
Constraints
0 and 500 nodes.-100 <= Node.val <= 1000 <= k <= 2 * 10⁹Rotating a list of n nodes n times puts it back as it was, so only k % n rotations matter. Count the nodes first, so a k of two billion costs no more than a small one, and watch out for the empty list.
Do the rotations by hand on a short list and watch what happens. With [3,8,1,9,4,6] and k = 2, the answer is [4,6,3,8,1,9]. The last two nodes moved to the front as one block, still in their old order, and the other four slid back behind them. Nothing else changed.
Time O(n)Space O(1)
The full walkthrough and code are part of Premium