You are given a linked list having ‘n’ nodes and an integer ‘k’.
You have to rotate the linked list to the right by ‘k’ positions .
Input: linked list = [1 2 3 4] , k = 2
Output: 3 4 1 2
Explanation:
We have to rotate the given linked list to the right 2 times. After rotating it to the right once it becomes 4->1->2->3. After rotating it to the right again, it becomes 3->4->1->2.
The first line of the input contains a single integer 'n', denoting the number of nodes in the linked list.
The next line contains 'n' space-separated integers, denoting the elements of the linked list.
The next line contains an integer ‘k’, representing the number of positions up to the given linked list that has to rotate.
Return the head of the linked list after rotating it.
You do not need to print anything, it has already been taken care of. Just implement the given function. Elements of your returned linked list will be printed in a single line.
6
1 2 3 4 5 6
2
5 6 1 2 3 4
For the first test case, after 1st clockwise rotation the modified linked list will be : 6->1->2->3->4->5
After, 2nd clockwise rotated the modified linked list will be : 5->6->1->2->3->4.
Thus the output is: 5 6 1 2 3 4.
3
3 6 9
0
3 6 9
In this test case, ‘k’ is 0 therefore there will be no rotation, so the linked list remains unchanged.
Try to do this in O(n).
1 <= n <= 10^5
0 <= Node.data <= 10^9
0 <= k <= 10^5
Time Limit: 1 sec
Do the changes at (K+1)th node from last.
Find the length of the Linked List to check whether the ‘K’ is greater than the Length of the Linked List or not. Take a modulo of ‘K’ with its length if it is greater than the length. Reach the (‘K’+1)th node from last and change the pointers of nodes to get a rotated Linked List.
Here is the algorithm:
O(N), where ‘N’ is the size of the Linked List.
Since we are traversing all nodes of the Linked List to find the length and after that we are rotating the first ‘K’ nodes of the Linked List. Hence, the overall time complexity will be O(N).
O(1)
Since we are not using any extra space, therefore space complexity will be O(1).