#C11436. Rotate Linked List

    ID: 40752 Type: Default 1000ms 256MiB

Rotate Linked List

Rotate Linked List

Given a singly linked list and a non-negative integer \( k \), rotate the list to the right by \( k \) places.

The rotation is performed by moving the last \( k \) nodes to the beginning of the list. For example, if the list is:

( 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5 )

and ( k = 2 ), then the resulting list will be:

( 4 \rightarrow 5 \rightarrow 1 \rightarrow 2 \rightarrow 3 ).

You should implement a solution with \( O(1) \) extra space.

inputFormat

The input consists of three parts:

  • The first line contains an integer \( n \) denoting the number of nodes in the linked list.
  • The second line contains \( n \) integers separated by spaces, representing the node values.
  • The third line contains the integer \( k \), the number of places to rotate the list.

outputFormat

Output the node values of the rotated linked list in one line, separated by a single space. If the list is empty, output an empty line.

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