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!
Delete Node B
Singly Linked List: Delete Node By Value
1 of 2
Algorithm
To solve this problem, we need to handle two cases:
Node to be deleted is head.
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.
HEAD
Singly Linked List: Delete Head Node
1 of 4
Now let’s go ahead and implement the case illustrated above in Python.
The class method delete_node takes key as an input parameter. On line 3, we’ll declare cur_node as self.head to have a starting point to traverse the linked list. To handle the case of deleting the head, we’ll check if cur_node is not None and if the data in cur_node is equal to key on line 5. Note that cur_node is pointing to the head of the linked list at this point. If key matches cur_node.data, we’ll update the head of the linked list (self.head) to cur_node.next, i.e., the next node of the previous head node (line 6). Once we have updated the head of the linked list, we’ll set the node to be deleted (cur_node) to None (line 7) and return from the method.
Now that we have written the code for deleting the head node let’s move on to the other case of deletion, deleting a node from a linked list which is not the head node.