Good morning! Here's our prompt for today.
Now that we've implemented a linked list, can you write a method that will delete all nodes of a given value?

You're given the following standard structure as the definition of a linked list
node:
JAVASCRIPT
1class LinkedListNode {
2 constructor(val) {
3 this.val = val;
4 this.next = null;
5 }
6}
The follow scenario is how we would invoke the method with a linked list
1 -> 2 -> 2 -> 5 -> 6
. As you can see, running the method results in removing all 2
s in the list.

JAVASCRIPT
1// head = 1 -> 2 -> 2 -> 5 -> 6
2// val = 2
3removeNodes(head, val);
4// 1 -> 5 -> 6
Constraints
- The value of the nodes as well as the value to be deleted are within integer limits (between
-1000000000
and1000000000
) - After deleting the nodes, you need to return the head of the new linked list
- The given linked list can be null
- In case all nodes are deleted, return null
- Expected time complexity :
O(n)
- Expected Space complexity :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
58
​
# delete node given its key
def removeNodes(head, key):
# fill
return head
​
​
# Node definition
class Node:
def __init__(self, val):
self.val = val
self.next = None
​
​
def create_nodes(head, nodes):
for val in nodes:
new_node = Node(val)
head.next = new_node
head = new_node
​
​
list1 = Node(3)
nodes1 = [4, 5, 6, 7, 8, 9, 10]
create_nodes(list1, nodes1)
​
list2 = Node(1)
nodes2 = [2, 3, 4, 5, 6, 7, 8]
create_nodes(list2, nodes2)
​
​
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
We'll now take you through what you need to know.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.