Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.
Examples:
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:
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .next = null ;
}
}
function push(head_ref , new_data) {
var new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
function printList(node) {
while (node != null ) {
document.write(node.data + " -> " );
node = node.next;
}
document.write( "null" );
}
function rightRotate(head , k) {
if (head == null )
return head;
var tmp = head;
var len = 1;
while (tmp.next != null ) {
tmp = tmp.next;
len++;
}
if (k > len)
k = k % len;
k = len - k;
if (k == 0 || k == len)
return head;
var current = head;
var cnt = 1;
while (cnt < k && current != null ) {
current = current.next;
cnt++;
}
if (current == null )
return head;
var kthnode = current;
tmp.next = head;
head = kthnode.next;
kthnode.next = null ;
return head;
}
var head = null ;
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
var k = 2;
var updated_head = rightRotate(head, k);
printList(updated_head);
</script>
|
Output:
4 -> 5 -> 1 -> 2 -> 3 -> NULL
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.
Please refer complete article on Clockwise rotation of Linked List for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
31 May, 2022
Like Article
Save Article