loading...

Deleting a node in a Linked list, when you have access to only that node.

dkp1903 profile image Dushyant Pathak ・1 min read

Deleting a node in a Linked list is a standard problem, until you are given the root of the LL, and the node that you want to delete. What if you want to delete that node?

Thought process:
Deleting a node requires a knowledge of the node before, to set the correct next link, and is not possible otherwise. So, how do we get a link to the node before?

Well, we have a link to the node, and we have a link to the next node. So, we can delete the next node. So, let's just shift the value of the next node here, and delete the next node!

del(Node* node)
{
    // Shifting the value
    node->val = node->next->val;
    // Removing the next node from the LL
    node->next = node->next->next;
}
Enter fullscreen mode Exit fullscreen mode

Thus, although it is the next node that has been kicked out of the Linked List, the value of the node that was to actually be deleted no longer exists! So, this works, as long as you are not asked to delete the actual node!

Happy coding!

Discussion

pic
Editor guide