DEV Community

Shubham_Baghel
Shubham_Baghel

Posted on

Merge Two Sorted Lists using recursion ,Leetcode Problem (Leetcode:21)

You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.

Image description

Solution: Here we are checking two list with empty case if any of list is null then it will return other list. After that we are trying to check value of first list is greater than values of second list then we are doing recursion based upon where we are passing Next pointer of first list and second list as parameter and vice versa.

Javascript solution:

var mergeTwoLists = function(list1, list2) {
     if (list1 === null) {
        return list2;
    }

    if (list2 === null) {
        return list1;
    }

    if (list1.val < list2.val) {
        list1.next = mergeTwoLists(list1.next, list2)
        return list1;

    } else {
        list2.next = mergeTwoLists(list1, list2.next)
        return list2;
    }
};
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)