DEV Community

Dushyant Pathak
Dushyant Pathak

Posted on

3 2

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

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!

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay