Remove Nth node from end of the Linked List | javascript program to delete nth node from last Structure of node ; Function to insert node in a linked list ; Function to remove nth node from last ; To store length of the linked list ; B > length , then we can 't remove node ; We need to remove head node ; Return head . next ; Remove len - B th node from starting ; This function prints contents of linked list starting from the given node ; Driver code
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function create ( head , x ) { var temp , ptr = head ; temp = new Node ( ) ; temp . data = x ; temp . next = null ; if ( head == null ) head = temp ; else { while ( ptr . next != null ) { ptr = ptr . next ; } ptr . next = temp ; } return head ; } function removeNthFromEnd ( head , B ) { var len = 0 ; var tmp = head ; while ( tmp != null ) { len ++ ; tmp = tmp . next ; } if ( B > len ) { document . write ( " " + len ) ; document . write ( " " + B + " " ) ; document . write ( " " ) ; return head ; } else if ( B == len ) { return head . next ; } else { var diff = len - B ; var prev = null ; var curr = head ; for ( i = 0 ; i < diff ; i ++ ) { prev = curr ; curr = curr . next ; } prev . next = curr . next ; return head ; } } function display ( head ) { var temp = head ; while ( temp != null ) { document . write ( temp . data + " " ) ; temp = temp . next ; } document . write ( " " ) ; } var head = null ; head = create ( head , 1 ) ; head = create ( head , 2 ) ; head = create ( head , 3 ) ; head = create ( head , 4 ) ; head = create ( head , 5 ) ; var n = 2 ; document . write ( " " ) ; display ( head ) ; head = removeNthFromEnd ( head , 2 ) ; document . write ( " " ) ; display ( head ) ;