VOOZH about

URL: https://www.geeksforgeeks.org/videos/rotate-a-linked-list-sgh8hr/

⇱ Rotate a Linked List - GeeksforGeeks | Videos


January 10, 2025 |5.8K 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/

Recommendations
720 Views | 21/06/2024...
PROBLEM OF THE DAY : 20/06/2024 | Integral Points Inside Triangle
1.3K Views | 16/06/2024...
PROBLEM OF THE DAY : 15/06/2024 | Mobile numeric keypad
840 Views | 08/06/2024...
PROBLEM OF THE DAY : 07/06/2024 | Maximum occured integer
390 Views | 07/06/2024...
PROBLEM OF THE DAY : 06/06/2024 | Max sum in the configuration
640 Views | 26/05/2024...
PROBLEM OF THE DAY : 25/05/2024 | You and your books
690 Views | 25/05/2024...
PROBLEM OF THE DAY : 24/05/2024 | Partitions with Given Difference
180 Views | 24/05/2024...
PROBLEM OF THE DAY : 23/05/2024 | K-Palindrome
1.2K Views | 23/05/2024...
PROBLEM OF THE DAY : 22/05/2024 | Minimize Max Distance to Gas Station
660 Views | 22/05/2024...
PROBLEM OF THE DAY : 21/05/2024 | K closest elements
320 Views | 21/05/2024...
PROBLEM OF THE DAY : 20/05/2024 | Modular Exponentiation for large numbers