Linked Lists Reversing and rewiring
301. Rotate List
You are given head, the first node of a singly linked list, and an integer k. Rotate the list to the
right by k places, and return the head of the rotated list.
Rotating to the right by one place moves the last node to the front, so 1 → 2 → 3 becomes 3 → 1 → 2.
Rotating by k places does that k times.
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The
output shows the list you return the same way. An empty list is null, which shows as [].
Example 1
Input: head = [3, 8, 1, 6, 4], k = 2
[6,4,3,8,1]Explanation: Rotating by one place moves 4 to the front, which gives 4 → 3 → 8 → 1 → 6. The second place moves 6 to the front.
Example 2
Input: head = [5, -2, 7], k = 4
[7,5,-2]Explanation: One place gives [7,5,-2], two give [-2,7,5], three give [5,-2,7], and four give [7,5,-2].
Example 3
Input: head = [], k = 6
[]Explanation: An empty list has no nodes to move, so the answer is the empty list.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 1090 ≤ k ≤ 2 × 109
Clarifying questions
What you would ask an interviewer before writing any code.