#K94392. Rotate Linked List

    ID: 38631 Type: Default 1000ms 256MiB

Rotate Linked List

Rotate Linked List

You are given a singly linked list and an integer k. Your task is to rotate the linked list to the right by k positions and return the modified list.

For example, given a linked list \(L = [a_1, a_2, \dots, a_n]\) and an integer \(k\), rotating the list means moving the last \(k\) nodes to the front. In mathematical terms, the rotated list becomes \(L' = [a_{n-k+1}, \dots, a_n, a_1, \dots, a_{n-k}]\), where \(k\) can be larger than \(n\) and effective rotation is \(k \% n\).

If the list is empty or contains a single node, or if k is zero (or a multiple of the list's length), then the list remains unchanged.

inputFormat

The input is provided via standard input with the following format:

  • The first line contains an integer n representing the number of nodes in the linked list. (0 ≤ n ≤ 10^5)
  • The second line contains n space-separated integers, the values of the nodes.
  • The third line contains an integer k representing the number of positions to rotate the list. (0 ≤ k ≤ 10^9)

outputFormat

Output the rotated linked list as a sequence of space-separated integers in a single line to standard output.

## sample
5
1 2 3 4 5
2
4 5 1 2 3