Clockwise rotation of Linked List | 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 povar to the new node ; A utility function to prvar 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 povar 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 ; * The constructed linked list is : 1.2 . 3.4 . 5 ; Rotate the linked list ; Print the rotated linked list
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 ( " " ) ; } 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 ) ;