Delete node in a Linked List
Problem Link
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
-
The linked list will contain at least two nodes.
-
The given node will not be the tail.
-
All node values are unique.
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:
-
Copy the value of the next node into the current node.
-
Set
node.next = node.next.next.
This simulates deleting the current node by replacing it with its next.
Approach
-
Copy the value of
node.nexttonode. -
Skip the
node.nextby settingnode.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:
-
node.val = node.next.val→node.val = 1 -
node.next = node.next.next→ skip the original 1
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.