Insert node into the middle of the linked list | Java implementation to insert node at the middle of the linked list ; head of list ; Node Class ; function to insert node at the middle of the linked list ; if list is empty ; get a new node ; assign values to the slow and fast pointers ; move slow pointer to next node ; move fast pointer two nodes at a time ; insert the ' newNode ' and adjust the required links ; function to display the linked list ; Driver program to test above ; Creating the list 1.2 . 4.5
import java . util . * ; import java . lang . * ; import java . io . * ; class LinkedList { static Node head ; static class Node { int data ; Node next ; Node ( int d ) { data = d ; next = null ; } } static void insertAtMid ( int x ) { if ( head == null ) head = new Node ( x ) ; else { Node newNode = new Node ( x ) ; Node slow = head ; Node fast = head . next ; while ( fast != null && fast . next != null ) { slow = slow . next ; fast = fast . next . next ; } newNode . next = slow . next ; slow . next = newNode ; } } static void display ( ) { Node temp = head ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } } public static void main ( String [ ] args ) { head = null ; head = new Node ( 1 ) ; head . next = new Node ( 2 ) ; head . next . next = new Node ( 4 ) ; head . next . next . next = new Node ( 5 ) ; System . out . println ( " Linked ▁ list ▁ before " + " ▁ insertion : ▁ " ) ; display ( ) ; int x = 3 ; insertAtMid ( x ) ; System . out . println ( " Linked list after " + ▁ " insertion : "); display ( ) ; } }