Problem 120
Rotate List
Medium · 20 pts · Linked List, Two Pointers
Problem
You are given a linked list and a number K. Rotate the list to the right by K places: in each rotation the last node moves to the front. Rotating a list of length N by N places gives the original list back, so only K mod N matters, and K can be very large. Find the length and the tail. Then the new tail is the node at position N - (K mod N) - 1 from the start: cut the list after it, and attach the old tail to the old head.
Input
First line: integers N and K. Second line: the N node values (empty if N = 0).
Output
Print the node values of the resulting list from head to tail, space-separated, or EMPTY if it has no nodes.
Constraints
0 <= N <= 500; 0 <= K <= 2000000000; -100 <= value <= 100
Example input
5 2 1 2 3 4 5
Example output
4 5 1 2 3
Explanation
Rotating 1 2 3 4 5 right by 2 moves the last two nodes, 4 and 5, to the front, giving 4 5 1 2 3.