Search⌘ K

Deletion by Value

Explore how to delete nodes by value in singly linked lists using Python. Learn to handle deletion of the head node and other nodes by traversing and updating pointers. This lesson guides you through the algorithm and its Python implementation, helping you effectively manage linked list deletion operations.

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.

Python 3.5
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 ...