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

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.

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay