Rotate Linked List

You have been given a Linked List having ‘N’ nodes and an integer ‘K’. You have to rotate the Linked List by ‘K’ positions in a clockwise direction.

Example :

 Given Linked List : 1 2 3 4 -1 and K : 2
 Then the modified Linked List after K rotation : 3 4 1 2
Input Format :
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case contains single space-separated integers, denoting the elements of the Linked List with -1 being the last element denoting the end of the List (or null element).

The next line of each test case contains an integer ‘K’, representing the number of positions up to the given Linked List that has to rotate.
Output Format :
For each test case, print the elements of the resultant Linked List after rotating by ‘K’ positions in a clockwise direction.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10^5
0 <= node.data <= 10^9 and node.data != -1 
0 <= ‘K’ <= 10^5

Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force

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. Reac...read more

CodingNinjas
author
2y
Circular Linked List

The basic idea of this approach is to first convert a linked list to circular linked list by making the last pointer point to head. Change the pointers of (K+1)th node to get a rot...read more

Help your peers!
Add answer anonymously...
PharmEasy Front end Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter