DEV Community

Cover image for Delete Node in a Linked List(in-place)
Hunter Heston
Hunter Heston

Posted on

3 1

Delete Node in a Linked List(in-place)

Problem on leetcode.com

We are asked to delete a node from a linked list. And we have to do this without knowing anything about this node's parent or the root of the linked list.

Assuming a node structure that looks like this:

function ListNode(value) {
     this.value = value;
     this.next = null;
}
Enter fullscreen mode Exit fullscreen mode

Let's go through the solution looking at this example:
A->B->C->D->E->null and assume we are asked to delete C.

We will not be able to see: A->B so our effective list is C->D->E->null. Since we can't see B we need to make C look like D without damaging the link that B already has to C.

Here are the steps to solve this problem:

  1. Copy D.value into C.value
  2. Copy D.next into C.next

Here is the JS code:

function deleteNode(node) {
  node.val = node.next.val
  node.next = node.next.next 
};
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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