DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

Leetcode - Merge Two Sorted Lists (with JavaScript)

Today I am going to show how to solve the Leetcode Merge Two Sorted Lists algorithm problem.

Here is the problem:
Alt Text

First, I create a dummy head node, which will help build a new linked list.
Then I compare the first elements of each list. I take whichever element is smaller and put it into a new linked list (= currentHead.next).
If one list was shorter than the other, then there are no longer two elements to compare. I therefore add the longer linked list to the end of the new linked list.

function ListNode(val) {
      this.val = val;
       this.next = null;
}

var mergeTwoLists = function(l1, l2) {
    let dummyHead = new ListNode(0);
    let currentNode = dummyHead; 

    while(l1 !== null && l2 !== null){

        if(l1.val < l2.val){
            currentNode.next = l1;
            l1 = l1.next
        } else {
            currentNode.next = l2
            l2 = l2.next
        }

        currentNode = currentNode.next
    }

    if(l1 !== null) {
        currentNode.next = l1;
    } else if (l2 !== null) {
        currentNode.next = l2
    }

    return dummyHead.next
}

Top comments (1)

Collapse
 
namhle profile image
Nam Hoang Le

Maybe you are wrong. You need 2 while loop after main while loop, instead of 2 if statements, in order to add ALL remain nodes.