Modify contents of Linked List | Linked list node ; Function to insert a node at the beginning of the linked list ; Allocate node ; Put in the data ; Link the old list at the end of the new node ; Move the head to point to the new node ; Function to print the linked list ; Function to middle node of list . ; Advance ' fast ' two nodes , and advance ' slow ' one node ; If number of nodes are odd then update slow by slow . next ; ; Function to modify the contents of the linked list . ; Create Stack . ; Traverse the list by using temp until stack is empty . ; Driver code ; creating the linked list ; Call Function to Find the starting point of second half of list . ; Call function to modify the contents of the linked list . ; Print the modified linked list
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def append ( 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 ( head ) : NEW_LINE INDENT if ( not head ) : NEW_LINE INDENT return ; NEW_LINE DEDENT while ( head . next != None ) : NEW_LINE INDENT print ( head . data , end = ' ▁ - > ▁ ' ) NEW_LINE head = head . next NEW_LINE DEDENT print ( head . data ) NEW_LINE DEDENT def find_mid ( head ) : NEW_LINE INDENT temp = head NEW_LINE slow = head NEW_LINE fast = head NEW_LINE while ( fast and fast . next ) : NEW_LINE INDENT slow = slow . next NEW_LINE fast = fast . next . next NEW_LINE DEDENT if ( fast ) : NEW_LINE INDENT slow = slow . next NEW_LINE DEDENT return slow NEW_LINE DEDENT def modifyTheList ( head , slow ) : NEW_LINE INDENT s = [ ] NEW_LINE temp = head NEW_LINE while ( slow ) : NEW_LINE INDENT s . append ( slow . data ) NEW_LINE slow = slow . next NEW_LINE DEDENT while ( len ( s ) != 0 ) : NEW_LINE INDENT temp . data = temp . data - s [ - 1 ] NEW_LINE temp = temp . next NEW_LINE s . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = append ( head , 10 ) NEW_LINE head = append ( head , 7 ) NEW_LINE head = append ( head , 12 ) NEW_LINE head = append ( head , 8 ) NEW_LINE head = append ( head , 9 ) NEW_LINE head = append ( head , 2 ) NEW_LINE mid = find_mid ( head ) NEW_LINE modifyTheList ( head , mid ) NEW_LINE print ( " Modified ▁ List : " ) NEW_LINE printList ( head ) NEW_LINE DEDENT