Delete node in a Linked List


237. Delete Node in a Linked List – LeetCode


Problem Statement

There is a singly linked list, and you are given a node that is guaranteed not to be the tail of the list.

Delete the node from the list, but you will not be given access to the head of the list.


Examples

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5. The linked list becomes 4 → 1 → 9 after calling your function.

Example 2:

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

Constraints


Intuition

You don’t have access to the previous node, so you can't directly remove the current node like in a normal deletion process.

Instead, we can:

This simulates deleting the current node by replacing it with its next.


Approach

  1. Copy the value of node.next to node.

  2. Skip the node.next by setting node.next = node.next.next.


Java Code

class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(1)
Space Complexity O(1)
Explanation Only modifies one node and pointer in constant time

Dry Run

Input:

List: 4 → 5 → 1 → 9, node = 5

Steps:

Output: 4 → 1 → 9


Conclusion

This is a tricky pointer manipulation problem where you're forced to think differently because you don’t have access to the previous node or the head.
It tests your understanding of what a "node" really represents in a linked list.