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:
- Copy D.value into C.value
- 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!
Top comments (0)