Insert a node after the n | structure of a node ; function to get a new node ; allocate memory for the node ; put in the data ; function to insert a node after the nth node from the end ; if list is empty ; get a new node for the value ' x ' ; Initializing the slow and fast pointers ; move ' fast _ ptr ' to point to the nth node from the beginning ; iterate until ' fast _ ptr ' points to the last node ; move both the pointers to the respective next nodes ; insert the ' newNode ' by making the necessary adjustment in the links ; function to print the list ; Creating list 1 -> 3 -> 4 -> 5
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function getNode ( data ) { var newNode = new Node ( ) ; newNode . data = data ; newNode . next = null ; return newNode ; } function insertAfterNthNode ( head , n , x ) { if ( head == null ) return ; var newNode = getNode ( x ) ; var slow_ptr = head ; var fast_ptr = head ; for ( var i = 1 ; i <= n - 1 ; i ++ ) fast_ptr = fast_ptr . next ; while ( fast_ptr . next != null ) { slow_ptr = slow_ptr . next ; fast_ptr = fast_ptr . next ; } newNode . next = slow_ptr . next ; slow_ptr . next = newNode ; } function printList ( head ) { while ( head != null ) { document . write ( head . data + " " ) ; head = head . next ; } } var head = getNode ( 1 ) ; head . next = getNode ( 3 ) ; head . next . next = getNode ( 4 ) ; head . next . next . next = getNode ( 5 ) ; var n = 4 , x = 2 ; document . write ( " " ) ; printList ( head ) ; insertAfterNthNode ( head , n , x ) ; document . write ( " " ) ; document . write ( " " ) ; printList ( head ) ;