user12130378
user12130378

Reputation:

how to remove all item from list in javascript

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

Upvotes: 1

Views: 182

Answers (2)

edu
edu

Reputation: 153

I apologize if I didn't understand the question, is this what you're looking for?

var removeElements = function (head, val) {
    if (!head) return null;

    let curr = head;
    let pre = null;

    while (curr != null) {
        if (curr.val == val) {
            if (pre) {
                pre.next = curr.next;
            } else {
                head = curr.next;
            }
        } else {
            pre = curr;
        }
        curr = curr.next;
    }

    return head;
};

Upvotes: 0

user12130378
user12130378

Reputation:

for special case I check like this

var removeElements = function (head, val) {
    if (!head) return null;

    while (head!=null){
        if(head.val == val){
            head = head.next;
        }else {
            break;
        }
    }

    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
};

Upvotes: 1

Related Questions