educative.io

Solution Review: Deletion by Value (Linked List)

from LinkedList import LinkedList
from Node import Node


def delete(lst, value):
    deleted = False
    if lst.is_empty():  # Check if list is empty -> Return False
        print("List is Empty")
        return deleted
    current_node = lst.get_head()  # Get current node
    previous_node = None  # Get previous node
    if current_node.data is value:
        lst.delete_at_head()  # Use the previous function
        deleted = True
        return deleted

    # Traversing/Searching for Node to Delete
    while current_node is not None:
        # Node to delete is found
        if value is current_node.data:
            # previous node now points to next node
            previous_node.next_element = current_node.next_element
            current_node.next_element = None
            deleted = True
            break
        previous_node = current_node
        current_node = current_node.next_element

    if deleted is False:
        print(str(value) + " is not in list!")
    else:
        print(str(value) + " deleted!")

    return deleted


lst = LinkedList()
lst.insert_at_head(1)
lst.insert_at_head(4)
lst.insert_at_head(3)
lst.insert_at_head(2)
lst.print_list()
delete(lst, 4)
lst.print_list()

In the above code, look at line no. 22 which says previous_node.next_element = current_node.next_element. Now, though I understand, this line will never get executed for first node since you have handled the condition of deleting first node above, this does not seem to be cleaner code as ideally “previous_node.next_element” cannot exists until it is assigned to current_node which happens only in line 26. Functionality wise this code will work, however, I feel one should avoid writing such a code where there is risk of accessing next_element for an object which is None.

Raising this as I got this as I got a comment on similar code one of my past interviews.

1 Like

Hi @Abhiram_Pattarkine,
At this point (line # 20), we know that our value to be deleted is not at the head so we can also move our lines 26 & 27 right after while current_node is not None:, now we have avoided the risk of accessing next_element for the object which is None. The nature of the function won’t change but it will have a reference before accessing next_element.

Please feel free to discuss anything else. Thank you.