Given a linked list, remove all nodes from it that match a given key.

For example,

Input:
 
Linked List: [4 -> 2 -> 4 -> 4 -> 5 -> 4 -> 7 -> 8 -> null]
key: 4
 
Output: 2 -> 5 -> 7 -> 8 -> null
 
 
Input:
 
Linked List: [1 -> 1 -> 1 -> null]
key: 1
 
Output: null

1. Iterative Solution

The idea is to loop through the linked list’s nodes, and for each node, remove the next node if its value matches the specified key. To handle the input where the first node matches the provided key, we can use a dummy node as the start of the result list. This dummy node is a temporary node that was allocated in the stack, and initially points to the head of the linked list. When we are done, the next pointer to the dummy node points to the head of the resulting list.

 
Following is the C++, Java, and Python program demonstrating it:

C++


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> nullptr

Java


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> null

Python


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> None

 
The time complexity of the above solution is O(n) and requires O(1) extra space. Here, n is the length of the linked list.

 
Here is a different approach that is structurally similar, but forgoes the use of a dummy head. Instead, it discards all nodes from the beginning of the linked list that match the specified key, before processing the remaining nodes.

C++


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> nullptr

Java


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> null

Python


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> None

2. Recursive Solution

The aforementioned iterative variant can easily be changed into a recursive one. The idea is to reach the end of the linked list by recursion and determine whether the current node’s value matches the supplied key. We return the next node if the current node’s data matches the supplied key; otherwise, we return the current node. Each node is connected to the remaining list as the recursion unfolds.

 
Following is the simple recursive implementation in C++, Java, and Python:

C++


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> nullptr

Java


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> null

Python


Download  Run Code

Output:

2 -> 5 -> 7 -> 8 -> None

The time complexity of the above solution is O(n), where n is the length of the linked list. The recursive version also need stack space proportional to the length of the list and are not advised for use in production.