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 (=
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; = null;

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

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

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

        currentNode =

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


Top comments (1)

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.