Clockwise rotation of Linked List | C ++ implementation of the approach ; Link list node ; A utility function to push a node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; A utility function to print linked list ; Function that rotates the given linked list clockwise by k and returns the updated head pointer ; If the linked list is empty ; len is used to store length of the linked list tmp will point to the last node after this loop ; If k is greater than the size of the linked list ; Subtract from length to convert it into left rotation ; If no rotation needed then return the head node ; current will either point to kth or NULL after this loop ; If current is NULL then k is equal to the count of nodes in the list Don 't change the list in this case ; current points to the kth node ; Change next of last node to previous head ; Change head to ( k + 1 ) th node ; Change next of kth node to NULL ; Return the updated head pointer ; Driver code ; The constructed linked list is : 1 -> 2 -> 3 -> 4 -> 5 ; Rotate the linked list ; Print the rotated linked list
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " ▁ - > ▁ " ; node = node -> next ; } cout << " NULL " ; } Node * rightRotate ( Node * head , int k ) { if ( ! head ) return head ; Node * tmp = head ; int 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 ; Node * current = head ; int cnt = 1 ; while ( cnt < k && current != NULL ) { current = current -> next ; cnt ++ ; } if ( current == NULL ) return head ; Node * kthnode = current ; tmp -> next = head ; head = kthnode -> next ; kthnode -> next = NULL ; return head ; } int main ( ) { Node * head = NULL ; push ( & head , 5 ) ; push ( & head , 4 ) ; push ( & head , 3 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; int k = 2 ; Node * updated_head = rightRotate ( head , k ) ; printList ( updated_head ) ; return 0 ; }