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 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 None after this loop ; If current is None 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 None ; 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 Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = ' ▁ - > ▁ ' ) NEW_LINE node = node . next NEW_LINE DEDENT print ( " NULL " ) NEW_LINE DEDENT def rightRotate ( head , k ) : NEW_LINE INDENT if ( not head ) : NEW_LINE INDENT return head NEW_LINE DEDENT tmp = head NEW_LINE len = 1 NEW_LINE while ( tmp . next != None ) : NEW_LINE INDENT tmp = tmp . next NEW_LINE len += 1 NEW_LINE DEDENT if ( k > len ) : NEW_LINE INDENT k = k % len NEW_LINE DEDENT k = len - k NEW_LINE if ( k == 0 or k == len ) : NEW_LINE INDENT return head NEW_LINE DEDENT current = head NEW_LINE cnt = 1 NEW_LINE while ( cnt < k and current != None ) : NEW_LINE INDENT current = current . next NEW_LINE cnt += 1 NEW_LINE DEDENT if ( current == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT kthnode = current NEW_LINE tmp . next = head NEW_LINE head = kthnode . next NEW_LINE kthnode . next = None NEW_LINE return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 1 ) NEW_LINE k = 2 NEW_LINE updated_head = rightRotate ( head , k ) NEW_LINE printList ( updated_head ) NEW_LINE DEDENT