how to remove Remove all elements from a linked list of integers that have value val.
example
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
I tried like this
var removeElements = function (head, val) {
if (!head) return null;
let curr = head,
pre = curr;
while (curr != null) {
if (curr.val == val) {
pre.next = curr.next
curr = curr.next;
} else {
pre = curr;
curr = curr.next;
}
}
return head
};
my first test case working fine
console.log(JSON.stringify(removeElements(
{
"val": 1,
"next": {
"val": 2,
"next": {
"val": 6,
"next":
{
"val": 3,
"next":
{
"val": 4,
"next":
{
"val": 5, "next":
{"val": 6, "next": null}
}
}
}
}
}
}
, 6)));
// working fine
// expected 1->2->3->4->5 or [1,2,3,4,5]
but it fail below case
console.log(JSON.stringify(removeElements(
{
"val": 1,
"next": {
"val": 1,
"next": null
}
}, 1)));
// getting {"val":1,"next":null} or [1]
// expected null or []
please suggest how to achieve this.I am storing the current node in previous node
head, since you returnheadall the time.if (head.val == val) { ... }while (head!=null){ if(head.val == val){ head = head.next; }else { break; } }