Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in linked list.
To rotate the linked list, we need to change next of kth node to NULL, next of last node to previous head node, and finally change 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 beginning and stop at kth node. Store pointer to kth node. We can get (k+1)th node using kthNode->next. Keep traversing till end and store pointer to last node also. Finally, change pointers as stated above.
Given linked list 10 20 30 40 50 60 Rotated Linked list 50 60 10 20 30 40
Time Complexity: O(n) where n is the number of nodes in Linked List. The code traverses the linked list only once.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Rotate the sub-list of a linked list from position M to N to the right by K places
- Rotate Doubly linked list by N nodes
- Rotate Linked List block wise
- Python | Ways to rotate a list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Convert singly linked list into circular linked list
- Merge a linked list into another linked list at alternate positions
- Check if a linked list is Circular Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Length of longest palindrome list in a linked list using O(1) extra space
- Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
- Sort a linked list of 0s, 1s and 2s
- Flattening a Linked List
- Linked List | Set 1 (Introduction)