Delete Node in a Linked List - Problem
Given a singly-linked list and a reference to a specific node to be deleted, write a function to delete that node from the linked list.
Important constraints:
- You are only given the node to be deleted - you do NOT have access to the head of the list
- All values in the linked list are unique
- The given node is guaranteed NOT to be the last node in the list
- The given node is guaranteed to be a valid node in the list
The goal is to make it so that:
- The value of the given node no longer exists in the linked list
- The number of nodes decreases by one
- All other values remain in the same relative order
Input & Output
Example 1 — Delete Middle Node
$
Input:
head = [4,5,1,9], node = 5
›
Output:
[4,1,9]
💡 Note:
The node with value 5 should be deleted. We copy the next node's value (1) to the current node, making it [4,1,1,9], then skip the next node to get [4,1,9].
Example 2 — Delete First Node
$
Input:
head = [4,5,1,9], node = 4
›
Output:
[5,1,9]
💡 Note:
Delete the first node by copying next node's value (5) to current node, then skipping the next node. Result: [5,1,9].
Example 3 — Two Node List
$
Input:
head = [1,2], node = 1
›
Output:
[2]
💡 Note:
In a two-node list, deleting the first node leaves only the second node. We copy value 2 to the first node and remove the second.
Constraints
- The number of nodes in the given linked list is in the range [2, 1000]
- -1000 ≤ Node.val ≤ 1000
- The value of each node in the linked list is unique
-
The
nodeto be deleted is in the linked list and is not a tail node
Visualization
Tap to expand
Understanding the Visualization
1
Input
Linked list [4,5,1,9] and node with value 5 to delete
2
Process
Copy next node's value and skip next node
3
Output
List becomes [4,1,9] with value 5 removed
Key Takeaway
🎯 Key Insight: When you can't delete yourself, become the next person and delete them instead
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code