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 ; 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 code ; Creating the list 1.2 . 4.5
code: using System ; public class LinkedList { static Node head ; 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 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 ) { Console . Write ( 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 ) ; Console . WriteLine ( " Linked ▁ list ▁ before " + " ▁ insertion : ▁ " ) ; display ( ) ; int x = 3 ; insertAtMid ( x ) ; Console . WriteLine ( " STRNEWLINE Linked ▁ list ▁ after " + " ▁ insertion : ▁ " ) ; display ( ) ; } }