DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

5 1

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay