DEV Community

loading...
Cover image for Delete Node in a Linked List(in-place)

Delete Node in a Linked List(in-place)

hunterheston profile image Hunter Heston ・1 min read

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;
}

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 
};

Thanks for reading!

Discussion (0)

Forem Open with the Forem app