
🚀 JS | ✅ merge Two Lists Problem with JS
#JS#ProblemSolving#Linkedlist#leetcodeImplementation of Linked-list
To solve this problem, we can use recursion
-
we do an equality check between head of 2 lists (if list1.val <= list2.val)
-
we call recursion (mergeTwoLists (list1.next, list2))
-
will repeat untill any list be null
-
then return first list
this image may helps you understand better.
✅ Javascript code implementation
var mergeTwoLists = function (list1, list2) {
if (!list1) return list2;
else if (!list2) return list1;
else if (list1.val <= list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2
}
};
🚀Runtime: 58 ms, faster than 59.60% of JavaScript online submissions for Merge Two Sorted Lists. 🚀Memory Usage: 44.6 MB, less than 12.91% of JavaScript online submissions for Merge Two Sorted Lists.
📢Follow in LinkedIn