Simple Recursive Solution C++ 14


  • 0
    G

    Merge Two sorted lists:
    This is a recursive solution to add two sorted lists. First we check that head is NULL or not then do the comparison

    ListNode *merge(ListNode *a,ListNode *b) {
            if(a==NULL)
                return b;
            if(b==NULL)
                return a;
            
            ListNode *r;
            if(a->val < b->val)
            {
                r=a;
                r->next=merge(a->next,b);
            }
            else
            {
                r=b;
                r->next=merge(a,b->next);
            }
            
            return r;
    }

  • 0
    D

    This recursive method seems to be no faster than iterative one, but obviously you declared fewer variables in this way.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.