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
57
console.log('PASSED: ' + 'removeNodes(list1, 10)');
var assert = require('assert');
​
function removeNodes(head, val) {
// Fill in this method
return head;
}
​
function Node(val) {
this.val = val;
this.next = null;
}
​
function LinkedListNode(val) {
this.val = val;
this.next = null;
}
​
var list1 = new LinkedListNode(3);
var nodes1 = [4, 5, 6, 7, 8, 9, 10];
createNodes(list1, nodes1);
​
var list2 = new LinkedListNode(1);
var nodes2 = [2, 3, 4, 5, 6, 7, 8];
createNodes(list2, nodes2);
​
function createNodes(head, nodes) {
for (let i = 0; i < nodes.length; i++) {
var newNode = new LinkedListNode(nodes[i]);
head.next = newNode;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
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.