Rotate a Linked List | Link list node ; This function rotates a linked list counter - clockwise and updates the head . The function assumes that k is smaller than size of linked list . ; Let us understand the below code for example k = 4 and list = 10.20 . 30.40 .50 . 60. ; Traverse till the end . ; Traverse the linked list to k - 1 position which will be last element for rotated array . ; Update the head_ref and last element pointer to None ; 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 ; Function to print linked list ; Driver code ; Start with the empty list ; Create a list 10.20 . 30.40 .50 . 60
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def rotate ( head_ref , k ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT current = head_ref NEW_LINE while ( current . next != None ) : NEW_LINE INDENT current = current . next NEW_LINE DEDENT current . next = head_ref NEW_LINE current = head_ref NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT current = current . next NEW_LINE DEDENT head_ref = current . next NEW_LINE current . next = None NEW_LINE return head_ref NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) 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 DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE for i in range ( 60 , 0 , - 10 ) : NEW_LINE INDENT head = push ( head , i ) NEW_LINE DEDENT print ( " Given ▁ linked ▁ list ▁ " ) NEW_LINE printList ( head ) NEW_LINE head = rotate ( head , 4 ) NEW_LINE print ( " Rotated Linked list   " ) NEW_LINE printList ( head ) NEW_LINE DEDENT