Rotate a singly linked list to the right by k positions.
Problem
Given the head of a singly linked list and a non-negative integer k, rotate the list to the right by k places.
A rotation moves the last node to the front of the list, one step at a time. After k rotations, return the new head of the list.
You should handle cases where k is larger than the length of the list efficiently.
Input Format
head: the head of a singly linked listk: number of right rotations
Output Format
- Return the head of the rotated linked list.
Constraints
- The list may be empty.
kis a non-negative integer.- Aim for an time solution and extra space solution.
Hints
- First find the length of the list and connect the tail to the head to form a cycle.
- Reduce
kusing the list length before choosing the new tail.
Input Format
head: singly linked list headk: non-negative integer
Output Format
- Return the head of the list after rotating right by
kpositions
Constraints
- The list may be empty
k >= 0- Prefer time and extra space
Example 1
Input
head = [1,2,3,4,5], k = 2
Output
[4,5,1,2,3]
Explanation
Rotating right by 2 moves the last two nodes to the front.
Example 2
Input
head = [0,1,2], k = 4
Output
[2,0,1]
Explanation
Since the length is 3, rotating by 4 is the same as rotating by 1.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.