DEV Community

codingpineapple
codingpineapple

Posted on

237. Delete Node in a Linked List (javascript solution)

Description:

Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.

It is guaranteed that the node to be deleted is not a tail node in the list.

Solution:

Time Complexity : O(1)
Space Complexity: O(1)

// Change node's val to the next node and then point node.next to node.next.next
// Because we never have to worry about node being tail we can always count on node.next.val and node.next.next to never be null
var deleteNode = function(node) {
    node.val = node.next.val
    node.next = node.next.next
};
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
tamb profile image
Tamb

What are these numbers from "237." etc?
Is there a worksheet I can follow?

Collapse
 
cod3pineapple profile image
codingpineapple

These problems are from leetcode.com. Here's the link to this one leetcode.com/problems/delete-node-...

Collapse
 
tamb profile image
Tamb

Oh wow. Thank you. This is very cool. I've been a web dev for about 5 years but have 0 formal CS experience. I'm getting a pro certificate in CS through edX. I will absolutely be using these problems to work on my skills. Thanks again for sharing!