Rotate a Linked List to the Right
Implement rotateRight
Given the head of a singly linked list and a non-negative integer
k, rotate the list to the right by k places and return the new head.
Rotating by the list's full length brings it back to where it started, so only k mod n actually changes anything — the optimal solution leans on that by briefly making the list circularTemporary Circular LinkLinking the tail back to the head turns "wrap around to the front" into an ordinary next-pointer walk — no special-casing needed for indices that would otherwise fall off the end. The list is cut back into a normal (acyclic) one before returning.: link the tail back to the head, walk to exactly where the new tail belongs, and cut the circle there. The next node after that cut — found correctly even when it wraps around past the original last node — becomes the new head.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Example 2:
Input: head = [1,2,3,4], k = 1
Output: [4,1,2,3]
Example 3:
Input: head = [1], k = 5
Output: [1]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes in head ≤ 500 - ●
-1000 ≤ node value ≤ 1000 - ●
0 ≤ k ≤ 2 × 10⁹
head =
[1, 2, 3, 4, 5]
k =
2