DEV Community

Akhil
Akhil

Posted on

Merge Two Sorted Lists

Question: Given two sorted linked lists, merge them!

eg:


List 1 : 1 -> 3 -> 5
List 2 : 2 -> 4 -> 6

Merged list: 1 -> 2 -> 3 -> 4 -> 5 -> 6

Enter fullscreen mode Exit fullscreen mode

If you've solved merge sort before, the approach is similar to that but here we have to play pointers. So let's play with them!

Algorithm :

Alt Text


var mergeTwoLists = function(l1, l2) {
    let dummy = new ListNode(-1);
    let head = dummy;
    while(l1!= null && l2 != null){
        if(l1.val<l2.val){
            head.next = l1;
            l1 = l1.next;
        }else{
            head.next = l2;
            l2 = l2.next;
        }
        head = head.next;
    }

    if(l1 != null){
        head.next = l1;
    }

    if(l2 != null){
        head.next = l2;
    }

    return dummy.next;
};

Enter fullscreen mode Exit fullscreen mode

That's it!

github : https://github.com/AKHILP96/Data-Structures-and-Algorithms/blob/master/problems/mergeTwoLinkedList.js

Top comments (0)