Leetcode - Merge Two Sorted Lists (with JavaScript)

urfan

Urfan Guliyev

Posted on June 21, 2020

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
}

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
urfan
Urfan Guliyev

Posted on June 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related