Understanding deletion at a given distance


In this final deletion form, we are incorporating the concepts we previously studied in the context of a singly linked list. The aim is to create a logical and comprehensive approach encompassing various scenarios. Although the process is similar to a singly linked list, keeping track of the previous node in each case requires additional effort. Here, the distance X is the 0 indexed position of the node to be deleted, counted from the head, so X = 0 means deleting the head and X = size of the list - 1 means deleting the tail. We will examine all the potential scenarios that need to be considered.

1. The list is empty

When the list is empty, meaning it contains no elements, any attempt to delete a node is unnecessary because there are no nodes in the list. Since there is nothing to remove, the list remains unchanged. We can return the existing head, as the list is empty, and no node needs to be deleted.

The list is empty

Algorithm

  • Step 1: Return the original head node.

2. X = 0

In this scenario, we must delete the head node, i.e., deleting the first node in the linked list. We should update the head to point to the second node in the linked list and set the previous pointer of the second node to null. After completing these steps, we can then delete the original head node.

Liking the course? Check our discounted plans to continue learning.