DDSA Solutions

237. Delete Node in a Linked List

Time: O(1)
Space: O(1)
Advertisement

Intuition

You don't have the previous node, but you have the node to delete. Copy the value from the next node into the current node, then skip the next node. The current node effectively becomes the next node.

Algorithm

  1. 1node.val = node.next.val.
  2. 2node.next = node.next.next.

Example Walkthrough

Input: head = [4,5,1,9], node = 5

  1. 1.Copy 1 (next's val) into node. node.next = node.next.next (skip old "1" node).
  2. 2.List: [4,1,9].

Output: [4,1,9]

Common Pitfalls

  • This only works because the problem guarantees node is not the tail.
237.cs
C#
// Approach: We are not given the head, so standard deletion by relinking from the previous node is impossible.
// Instead, copy the next node's value into the current node and skip the next node.
// node.val = node.next.val; node.next = node.next.next;
// This effectively 'moves' the next node into the current position, achieving the same observable effect.
// Guaranteed by the problem: the node to delete is never the tail node.
// Time: O(1) Space: O(1).

public class ListNode
{
    public int val;
    public ListNode next;
    public ListNode(int x) { val = x; }
}

public class Solution
{
    public void DeleteNode(ListNode node)
    {
        if (node.next != null)
        {
            node.val = node.next.val;
            node.next = node.next.next;
        }
    }
}
Advertisement
Was this solution helpful?