Modify contents of Linked List | Java 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
import java . util . * ; 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 head ) { if ( head == null ) { return ; } while ( head . next != null ) { System . out . print ( head . data + " - > " ) ; head = head . next ; } System . out . print ( head . data + "NEW_LINE"); } static Node find_mid ( Node head ) { Node temp = head , slow = head , fast = head ; while ( fast != null && fast . next != null ) { slow = slow . next ; fast = fast . next . next ; } if ( fast != null ) { slow = slow . next ; } return slow ; } static void modifyTheList ( Node head , Node slow ) { Stack < Integer > s = new Stack < Integer > ( ) ; Node temp = head ; while ( slow != null ) { s . add ( slow . data ) ; slow = slow . next ; } while ( ! s . empty ( ) ) { temp . data = temp . data - s . peek ( ) ; temp = temp . next ; s . pop ( ) ; } } public static void main ( String [ ] args ) { Node head = null , mid ; head = push ( head , 10 ) ; head = push ( head , 7 ) ; head = push ( head , 12 ) ; head = push ( head , 8 ) ; head = push ( head , 9 ) ; head = push ( head , 2 ) ; mid = find_mid ( head ) ; modifyTheList ( head , mid ) ; System . out . print ( " Modified ▁ List : " + "NEW_LINE"); printList ( head ) ; } }