DEV Community

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

Posted on

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!

Top comments (0)