Modify contents of Linked List | C ++ implementation to modify the contents of the 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 program to test above ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printList ( struct Node * ) ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = * head_ref ; * head_ref = new_node ; } void printList ( struct Node * head ) { if ( ! head ) return ; while ( head -> next != NULL ) { cout << head -> data << " ▁ - > ▁ " ; head = head -> next ; } cout << head -> data << endl ; } Node * find_mid ( Node * head ) { Node * temp = head , * slow = head , * fast = head ; while ( fast && fast -> next ) { slow = slow -> next ; fast = fast -> next -> next ; } if ( fast ) slow = slow -> next ; return slow ; } void modifyTheList ( struct Node * head , struct Node * slow ) { stack < int > s ; Node * temp = head ; while ( slow ) { s . push ( slow -> data ) ; slow = slow -> next ; } while ( ! s . empty ( ) ) { temp -> data = temp -> data - s . top ( ) ; temp = temp -> next ; s . pop ( ) ; } } int main ( ) { struct Node * head = NULL , * mid ; push ( & head , 10 ) ; push ( & head , 7 ) ; push ( & head , 12 ) ; push ( & head , 8 ) ; push ( & head , 9 ) ; push ( & head , 2 ) ; mid = find_mid ( head ) ; modifyTheList ( head , mid ) ; cout << " Modified ▁ List : " << endl ; printList ( head ) ; return 0 ; }