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 : NEW_LINE INDENT def __init__ ( self , new_data ) : NEW_LINE INDENT self . data = new_data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def deleteLast ( head , x ) : NEW_LINE INDENT temp = head NEW_LINE ptr = None NEW_LINE while ( temp != None ) : NEW_LINE INDENT if ( temp . data == x ) : NEW_LINE INDENT ptr = temp NEW_LINE DEDENT temp = temp . next NEW_LINE DEDENT if ( ptr != None and ptr . next == None ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp . next != ptr ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT temp . next = None NEW_LINE DEDENT if ( ptr != None and ptr . next != None ) : NEW_LINE INDENT ptr . data = ptr . next . data NEW_LINE temp = ptr . next NEW_LINE ptr . next = ptr . next . next NEW_LINE DEDENT return head NEW_LINE DEDENT def newNode ( x ) : NEW_LINE INDENT node = Node ( 0 ) NEW_LINE node . data = x NEW_LINE node . next = None NEW_LINE return node NEW_LINE DEDENT def display ( head ) : NEW_LINE INDENT temp = head NEW_LINE if ( head == None ) : NEW_LINE INDENT print ( " None " ) NEW_LINE return NEW_LINE DEDENT while ( temp != None ) : NEW_LINE INDENT print ( temp . data , " ▁ - > ▁ " , end = " " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( " None " ) NEW_LINE DEDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next = newNode ( 5 ) NEW_LINE head . next . next . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next . next . next = newNode ( 4 ) NEW_LINE print ( " Created ▁ Linked ▁ list : ▁ " ) NEW_LINE display ( head ) NEW_LINE head = deleteLast ( head , 4 ) NEW_LINE print ( " List ▁ after ▁ deletion ▁ of ▁ 4 : ▁ " ) NEW_LINE display ( head ) NEW_LINE