Delete Node in Linked List
LeetCode Problem #237 (Easy)
Problem Statement
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Testcases
Prerequisite Knowledge
General Approach
Conventionally, to delete a particular node, we would modify the pointer of the node before the node to be deleted to point to the node after the node to be deleted.
In this example, Node 3 must be deleted. The node before it is Node 2 and the node after it is Node 4. We modify the pointer of Node 2 to point to Node 4. This would cut off the link between Node 2 and Node 3, effectively "deleting" the node from the list.
However, we do not have access to the previous node in this problem, so we cannot modify this node to solve the problem.
Algorithm
Swap Nodes Approach
Replace the value of the node to be deleted with the value of the node next to it.
Set the pointer of the node to be deleted to the node next to its adjacent node.
Now, we can intuitively apply the approach that was discussed before remove the link to the next node, effectively "deleting" Node 3.
Code
Last updated
Was this helpful?