My Javascript Implementation


  • 1
    H

    Can you guys comment on my Javascript implementation on this problem? It's 199 ms :/

    var removeElements = function (head, val) {
    var pointer = head;
    var prev = null;

        while(pointer){
            if(pointer.val === val){
                if(pointer === head){ // same object
                    head = head.next;
                    pointer = head;//new head
                } else if(prev){
                    prev.next = pointer.next; 
                    pointer = pointer.next;
                } 
            } else {
                prev = pointer;
                if(pointer){
                    pointer = pointer.next;   
                }
            }
        }
        return head;
    };

  • 1
    R

    I think it's good. you can look at the distribution of the javascript solutions.
    You can maybe make it a tiny bit faster via removing a few unneeded condition checks such as the "if (pointer)" and the "else if(prev)"


  • 1
    W

    A little late, but if you switch the order of

    if(pointer === head){ // same object
                head = head.next;
                pointer = head;//new head
            } else if(prev){
                prev.next = pointer.next; 
                pointer = pointer.next;
            } 
    

    so that you first check that it is not the head then it goes a quite a bit faster.

    if(pointer !== head){ // same object
                 prev.next = pointer.next; 
                pointer = pointer.next;
            } else {
                head = head.next;
                pointer = head;//new head
               
            } 

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.