In this example we will see how to remove specific elements from linked list. Here we will pass value to be removed and list as an input. Finally We will return the list with removed elements.
In above example we can see 9 has been removed and new list without 9 has been returned.
head = [1,2,9,3]
val = 9
var removeVal = function(head, val) {
while (head != null && head.val == val) {
head = head.next;
}
let curr = head;
while(curr && curr.next){
if(curr.next.val !== val){
curr = curr.next;
}else{
curr.next = curr.next.next;
}
}
return head
};
// Output [1,2,3]
var removeVal = function(head, val) {
if (head == null) return null;
head.next = removeVal(head.next, val);
return head.val == val ? head.next : head;
}
// Output [1,2,3]