DEV Community

Akhil
Akhil

Posted on

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay