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 ; Constructor to create a new node ; function to insert node at the middle of the linked list ; if list is empty ; get a new node ; calculate length of the linked list , i . e , the number of nodes ; ' count ' the number of nodes after which the new node is to be inserted ; ' ptr ' points to the node after which the new node is to be inserted ; 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 ptr = head ; int len = 0 ; while ( ptr != null ) { len ++ ; ptr = ptr . next ; } int count = ( ( len % 2 ) == 0 ) ? ( len / 2 ) : ( len + 1 ) / 2 ; ptr = head ; while ( count -- > 1 ) ptr = ptr . next ; newNode . next = ptr . next ; ptr . 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 ( ) ; } }