Given a singly singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2
Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULL
Input: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL, K = 12
Output: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL
Approach: To rotate the linked list first check whether the given k is greater than the count of nodes in the linked list or not. Traverse the list and find the length of the linked list then compare it with k, if less then continue otherwise deduce it in the range of linked list size by taking modulo with the length of the list.
After that subtract the value of k from the length of the list. Now, the question has been changed to the left rotation of the linked list so follow that procedure:
- Change the next of the kth node to NULL.
- Change the next of the last node to the previous head node.
- Change the head to (k+1)th node.
In order to do that, the pointers to the kth node, (k+1)th node and last node are required.
Below is the implementation of the above approach:
4 -> 5 -> 1 -> 2 -> 3 -> NULL
Time Complexity: O(n) where n is the number of nodes in Linked List.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Clockwise rotation of Doubly Linked List by N places
- Left Rotation and Right Rotation of a String
- Anti Clockwise spiral traversal of a binary tree
- Clockwise Spiral Traversal of Binary Tree | Set - 2
- Check if a string can be formed from another string by at most X circular clockwise shifts
- Reverse Clockwise spiral traversal of a binary tree
- Reverse Anti Clockwise Spiral Traversal of a Binary Tree
- Rotate a matrix by 90 degree in clockwise direction without using any extra space
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Create new linked list from two given linked list with greater element at each node
- Check if a linked list is Circular Linked List
- Convert Singly Linked List to XOR Linked List
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- Program for array rotation
- Block swap algorithm for array rotation
- Lexicographically minimum string rotation | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.