Rotate List
mediumLinked List & Stack II+20 XPTime limit 2s
Rotate a linked list to the right by k places: one rotation moves the tail node to the front. For example, 1 2 3 4 5 rotated by 2 is 4 5 1 2 3.
List format. A linked list is given as two lines: its length n, then its n values from head to tail (the second line is empty when n = 0). When you print a list, print its values on one line separated by spaces, or the word empty if it has no nodes.
Input: one list, then a third line k.
Output: the rotated list (empty for an empty list).
Constraints: 0 ≤ n ≤ 10⁵, 0 ≤ k ≤ 2·10⁹, −1000 ≤ value ≤ 1000.
Think about it: k can be far bigger than n, and rotating n times gives back the same list — so only k mod n matters. Find the length and the tail, join the tail to the head to make a ring, then cut the ring at the right place.
Sample input 1
5 1 2 3 4 5 2
Sample output 1
4 5 1 2 3
Sample input 2
3 0 1 2 4
Sample output 2
2 0 1
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).