text: Insert node into 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 ; Creating the list 1.2 . 4.5
code: var head ; class Node { constructor ( val ) { this . data = val ; this . next = null ; } } function insertAtMid ( x ) { if ( head == null ) head = new Node ( x ) ; else { var newNode = new Node ( x ) ; var slow = head ; var fast = head . next ; while ( fast != null && fast . next != null ) { slow = slow . next ; fast = fast . next . next ; } newNode . next = slow . next ; slow . next = newNode ; } } function display ( ) { var temp = head ; while ( temp != null ) { document . write ( temp . data + " " ) ; temp = temp . next ; } } head = null ; head = new Node ( 1 ) ; head . next = new Node ( 2 ) ; head . next . next = new Node ( 4 ) ; head . next . next . next = new Node ( 5 ) ; document . write ( " " + " " ) ; display ( ) ; var x = 3 ; insertAtMid ( x ) ; document . write ( " " + " " ) ; display ( ) ;