Clockwise rotation of Linked List | Java 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
class GFG { static class Node { int data ; Node next ; } static Node 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 ; return head_ref ; } static void printList ( Node node ) { while ( node != null ) { System . out . print ( node . data + " ▁ - > ▁ " ) ; node = node . next ; } System . out . print ( " null " ) ; } static Node rightRotate ( Node head , int k ) { if ( head == null ) 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 ; } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 5 ) ; head = push ( head , 4 ) ; head = push ( head , 3 ) ; head = push ( head , 2 ) ; head = push ( head , 1 ) ; int k = 2 ; Node updated_head = rightRotate ( head , k ) ; printList ( updated_head ) ; } }