Posted on 27 March 2010
Given a linked list, and a node in the list. How do you delete this very node from the linked list. You may safely assume that the node is not the last node of the list.
Consider the following linked list, with the last node being Z. We need to delete a given node from this list. Remember we are in a singly linked list and hence we cannot traverse back in the node.
Consider a case where the node is not the second last node. For example, we need to delete the node W from the list. Swap the value of node W with the next node X. Thus, the list would somewhat look like,
Now point the original node to the node pointed by the forward node i.e., make X point directly to Y, instead of W.
And we have deleted the original node.
For the case where the node being deleted is the last node, just make the node point to
NULL, i.e. make it the tail/terminating node of the linked list.
Hope this helps.