Delete last occurrence of an item from linked list | A linked list Node ; Function to delete the last occurrence ; If found key , update ; If the last occurrence is the last node ; If it is not the last node ; Utility function to create a new node with given key ; This function prints contents of linked list starting from the given Node ; Driver code
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function deleteLast ( head , x ) { var temp = head , ptr = null ; while ( temp != null ) { if ( temp . data == x ) ptr = temp ; temp = temp . next ; } if ( ptr != null && ptr . next == null ) { temp = head ; while ( temp . next != ptr ) temp = temp . next ; temp . next = null ; } if ( ptr != null && ptr . next != null ) { ptr . data = ptr . next . data ; temp = ptr . next ; ptr . next = ptr . next . next ; } } function newNode ( x ) { var node = new Node ( ) ; node . data = x ; node . next = null ; return node ; } function display ( head ) { var temp = head ; if ( head == null ) { document . write ( " " ) ; return ; } while ( temp != null ) { document . write ( temp . data + " " ) ; temp = temp . next ; } document . write ( " " ) ; } var head = newNode ( 1 ) ; head . next = newNode ( 2 ) ; head . next . next = newNode ( 3 ) ; head . next . next . next = newNode ( 4 ) ; head . next . next . next . next = newNode ( 5 ) ; head . next . next . next . next . next = newNode ( 4 ) ; head . next . next . next . next . next . next = newNode ( 4 ) ; document . write ( " " ) ; display ( head ) ; deleteLast ( head , 4 ) ; document . write ( " " ) ; display ( head ) ;