text: Insert node into 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 ; Creating the list 1.2 . 4.5
code: var head ; class Node { constructor ( d ) { this . data = d ; this . next = null ; } } function insertAtMid ( x ) { if ( head == null ) head = new Node ( x ) ; else { var newNode = new Node ( x ) ; var ptr = head ; var len = 0 ; while ( ptr != null ) { len ++ ; ptr = ptr . next ; } var count = ( ( len % 2 ) == 0 ) ? ( len / 2 ) : ( len + 1 ) / 2 ; ptr = head ; while ( count -- > 1 ) ptr = ptr . next ; newNode . next = ptr . next ; ptr . next = newNode ; } } function display ( ) { var temp = head ; while ( temp != null ) { document . write ( temp . data + " " ) ; temp = temp . next ; } } 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 ( ) ;