Clean and easy understand javascript solution (but why this is so slow in js ranking?)


  • 0
    A
    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var mergeTwoLists = function(l1, l2) {
        var result = new ListNode(0);
        var newHead = result;
        while(l1 || l2){
            if(l1 === null){
                result.next = l2;
                return newHead.next;
            }
            else if(l2 === null){
                result.next = l1;
                return newHead.next;
            }
            if(l1.val < l2.val){
                var newNode = new ListNode(l1.val);
                result.next = newNode;
                result = newNode;
                l1 = l1.next;
            }
            else if(l1.val > l2.val){
                newNode = new ListNode(l2.val);
                result.next = newNode;
                result = newNode;
                l2 = l2.next;
            }
            else{
                newNode = new ListNode(l2.val);
                result.next = newNode;
                result = newNode;
                l2 = l2.next;
            }
        }
        return newHead.next;
    };

  • 0
    F

    if you reuse nodes from existing lists (l1,l2) you might get faster runtime - since the problem did not saied to keep intact the input.

    also you might want to look how not to do all the checks in the while loop :

    for example
    while(l1 && l2 ){
    if(l1.val < l2.val){
    var newNode = new ListNode(l1.val);
    result.next = newNode;
    result = newNode;
    l1 = l1.next;
    }
    else if(l1.val > l2.val){
    newNode = new ListNode(l2.val);
    result.next = newNode;
    result = newNode;
    l2 = l2.next;
    }
    else{
    newNode = new ListNode(l2.val);
    result.next = newNode;
    result = newNode;
    l2 = l2.next;
    }
    }


  • 0
    A

    Thanks @florin5 !
    Looks like I have lots of things to learn!


Log in to reply
 

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