text: Insert node into the middle of the linked list | C # 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 code ; Creating the list 1.2 . 4.5
code: using System ; public class LinkedList { static Node head ; public class Node { public int data ; public Node next ; public 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 ) { Console . Write ( temp . data + " ▁ " ) ; temp = temp . next ; } } public static void Main ( ) { head = null ; head = new Node ( 1 ) ; head . next = new Node ( 2 ) ; head . next . next = new Node ( 4 ) ; head . next . next . next = new Node ( 5 ) ; Console . WriteLine ( " Linked ▁ list ▁ before ▁ " + " insertion : ▁ " ) ; display ( ) ; int x = 3 ; insertAtMid ( x ) ; Console . WriteLine ( " STRNEWLINE Linked ▁ list ▁ after " + " ▁ insertion : ▁ " ) ; display ( ) ; } }