• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
August 16, 2024 |2.4K Views

Rotate a Linked List

Description
Discussion

Given a singly linked list, The task is to rotate the linked list counter-clockwise by k nodes.

Examples:

Input: linked list = 10->20->30->40->50->60, k = 4
Output: 50->60->10->20->30->40. 


Explanation: k is smaller than the count of nodes in a linked list so (k+1 )th node i.e. 50 becomes the head node and 60’s next points to 10

Input: linked list = 30->40->50->60, k = 2
Output: 50->60->30->40.

Approach: Below is the idea to solve the problem:

To rotate the linked list, we need to change the next pointer of kth node to NULL, the next pointer of the last node should point to the previous head node, and finally, change the head to (k+1)th node. So we need to get hold of three nodes: kth node, (k+1)th node, and last node. 


Traverse the list from the beginning and stop at kth node. store k’s next in a tem pointer and point k’s next to NULL then start traversing from tem and keep traversing till the end and point end node’s next to start node and make tem as the new head.

Related Article : https://www.geeksforgeeks.org/rotate-a-linked-list/