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 ' ; find length of the list , i . e , the number of nodes in the list ; traverse up to the nth node from the end ; 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 ptr = head ; var len = 0 , i ; while ( ptr != null ) { len ++ ; ptr = ptr . next ; } ptr = head ; for ( i = 1 ; i <= ( len - n ) ; i ++ ) ptr = ptr . next ; newNode . next = ptr . next ; 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 ) ;