Problem name: Merge Two Sorted Lists
Problem statement:
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = [] Output: [] Solution: Simple solution using recursion.
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* temp;
if(l1 == NULL) return l2;
else if(l2 == NULL) return l1;
if(l1->val < l2->val){
temp = l1;
temp->next = mergeTwoLists(l1->next, l2);
}
else{
temp = l2;
temp->next = mergeTwoLists(l1, l2->next);
}
return temp;
}
};

Leave a comment