#K63322. Rotate Linked List
Rotate Linked List
Rotate Linked List
You are given a singly linked list and a non-negative integer \(k\). Your task is to rotate the list to the right by \(k\) positions. In other words, each node in the list is moved \(k\) positions forward, and nodes that fall off the end are attached back at the beginning of the list.
For example, given the list [1, 2, 3, 4, 5]
and \(k = 2\), the rotated list is [4, 5, 1, 2, 3]
.
You must implement an algorithm with \(O(n)\) time complexity and \(O(1)\) auxiliary space.
inputFormat
The input is read from standard input and consists of three lines:
- The first line contains an integer \(n\), the number of nodes in the list.
- The second line contains \(n\) space-separated integers representing the values of the nodes. If \(n = 0\), this line will be empty.
- The third line contains an integer \(k\), the number of positions to rotate the list to the right.
outputFormat
Output a single line to standard output containing the values of the rotated list separated by a single space. If the list is empty, output an empty line.
## sample5
1 2 3 4 5
2
4 5 1 2 3