mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
18 lines
467 B
C++
18 lines
467 B
C++
class Solution{
|
|
public :
|
|
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
|
|
if(!l1 || !l2)
|
|
return l1? l1: l2;
|
|
if(l1->val > l2->val)
|
|
swap(l1,l2);
|
|
l1->next = mergeTwoLists(l1->next, l2);
|
|
return l1;
|
|
|
|
}
|
|
}
|
|
|
|
//At every step, pick the smaller head node, attach it to the result,and recursively merge the remaining lists
|
|
//TC : O(m+n)
|
|
//SC: O(m+n), recursion stack space
|
|
|