Delete Node in a Linked List - Complete Solution Guide
Delete Node in a Linked List is LeetCode problem 237, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
There is a singly-linked list head and we want to delete a node node in it. You are given the node to be deleted node . You will not be given access to the first node of head . All the values of the linked list are unique , and it is guaranteed that the given node node is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: The value of the given node should not exist in the linked list. The number of nodes
Detailed Explanation
The problem asks us to delete a given node from a singly linked list. Crucially, we are *not* given the head of the list, only the node to be deleted. We also know that the given node is guaranteed not to be the last node in the list. The task is to effectively remove the given node from the linked list without having direct access to the nodes before it. By deleting, we mean modifying the linked list such that the deleted node's value is no longer present, the number of nodes is reduced by one, and the order of remaining nodes is preserved.
Solution Approach
The solution takes advantage of the fact that we are given the node to delete and that this node is not the tail. Instead of directly deleting the node, we overwrite the node's value with the value of its immediate successor. Then, we effectively remove the successor by updating the 'next' pointer of the current node to point to the node after the successor. This effectively deletes the *next* node, but achieves the goal of removing the value of the original node we wanted to delete.
Step-by-Step Algorithm
- Step 1: Copy the value of the next node (node.next.val) into the current node (node.val).
- Step 2: Update the 'next' pointer of the current node (node.next) to point to the node after the next node (node.next.next). This effectively removes the next node from the linked list.
Key Insights
- Insight 1: Since we don't have access to the previous node, we can't simply re-link the 'next' pointer of the previous node to skip the node to be deleted.
- Insight 2: Because we can't directly remove the node, we can overwrite the node's value with the value of the next node and then remove the next node.
- Insight 3: The restriction that the node to be deleted is not the tail node is essential for this approach to work.
Complexity Analysis
Time Complexity: O(1)
Space Complexity: O(1)
Topics
This problem involves: Linked List.
Companies
Asked at: Nvidia, Oracle, PayPal.