Removing Nodes from a Linked List
As a final step, let’s add the code to remove a node. For this to work, we need to know which node to remove. The process of removing it involves routing the link from the previous node to the node that follows the node to be removed. This is shown in the following image.
With appropriate prompts, copilot can implement this for us. We need to check the basic logic, and the different cases that may need special attention, primarily removing the first node, removing the last node, and removing the only node.
Here is what Copilot created for me. It handles the removal of the first node, and last node. It clears the node, and even added the code to search for the previous node for me. I added some extra comments to make sure we can follow the code going forward.
This is a case when the code is pretty convincing, until you look and think about it. The check for removing the last node, has the wrong logic. The new last node should be the node before not after the node we are removing.
Similarly, we don’t need to search for the previous node if we removed the first node. We should move searching for the previous node into an else branch, so it is skipped if we know we removed the first node.
Lastly, the node
parameter will hide the node
data type. We need to think of a new name for this parameter.
We can move this around to fix it up. This took some thinking, as we need to make sure we handle different cases we identified above (remove first, last, and only nodes). Here is what I came up with.