Merge Two Sorted Lists using recursion ,Leetcode Problem (Leetcode:21)
Shubham_Baghel
Posted on July 5, 2022
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.
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;
}
};
💖 💪 🙅 🚩
Shubham_Baghel
Posted on July 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.