Rotate a Linked List

Medium

Given a linked list, rotate it to the right by k nodes.

Examples:

Input: 1→2→3→4
k: 3
Output: 2→3→4→1

Input: 1→2→3
k: 4
Output: 3→1→2

Testing

Input Format

The first line contains an integer ‘T’, denoting the number of test cases.

For each test case the input has three lines:

  • An integer ‘n’ denoting the length of the linked list.
  • n space-separated integers denoting elements of the linked list.
  • An integer ‘k’ denoting the number of right-shifts you need to perform.

Output Format

For each test case, a line containing space-separated elements of the linked list after rotation.

Sample Input

2
4
5 4 3 1
2
5
1 2 3 4 5
6

Expected Output

3 1 5 4
5 1 2 3 4

Constraints

1 <= T <= 100
0 <= n <= 104
0 <= k <= 109
1 <= elements <= 105

Editorial Link: Editorial