Deletion by Value

In this lesson, we will learn how to delete a node based on a value from a linked list.

In this lesson, we will investigate singly-linked lists by focusing on how one might delete a node in the linked list. In summary, to delete a node, we’ll first find the node to be deleted by traversing the linked list. Then, we’ll delete that node and update the rest of the pointers. That’s it!

Algorithm #

To solve this problem, we need to handle two cases:

  1. Node to be deleted is head.
  2. Node to be deleted is not head.

Case of Deleting Head #

Let’s look at the illustration below to get a fair idea of the steps that we are going to follow while writing the code.

Now let’s go ahead and implement the case illustrated above in Python.

Press + to interact
def delete_node(self, key):
cur_node = self.head
if cur_node and cur_node.data == key:
self.head = cur_node.next
cur_node = None
return

The class method delete_node takes ...