Solution: Remove Linked List Elements
Let’s solve the Remove Linked List Elements problem using the In-place Manipulation of a Linked List pattern.
We'll cover the following
Statement
You are given the head of a linked list and an integer k
. Remove all nodes from the linked list where the node’s value equals k
, and return the head of the updated list.
Constraints:
The number of nodes in the list is in the range
. Node.data
k
Solution
The core intuition behind solving this problem is to modify the linked list in place. We create a dummy node to handle scenarios where the head node needs removal. Additionally, we use two pointers for traversal: one to keep track of the previous node and the other to track the current node. We iterate through the linked list and check if the current node’s data equals k
. If it is, we remove this node from the linked list by updating the next link of the previous node. If the current node’s data doesn’t match k
, we move both pointers forward to process the next nodes.
Using the above intuition, the solution can be implemented as follows:
Create a dummy node pointing to the head of the linked list. This helps us handle edge cases, like removing the head node, without needing special checks.
Initialize two pointers for traversal:
prev
starts at the dummy node, andcurr
starts at the head of the linked list.Iterate through the linked list:
If the
curr
node’s value matchesk
, we remove this node from the linked list by updatingnext
ofprev
tonext
ofcurr
. We also delete this node if needed. Then, we movecurr
to the next node.If the
curr
node’s value does not matchk
, move bothprev
andcurr
forward to process the next node.
After traversing the complete linked list, we return the updated list’s head stored in the
next
of the dummy node. We also delete the dummy node if need be.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.