My easy solution O(n+m) 6ms use C


  • 0
    1

    /**

    • Definition for singly-linked list.
    • struct ListNode {
    • int val;
      
    • struct ListNode *next;
      
    • };
      */

    struct ListNode* insert(int);
    struct ListNode** min(struct ListNode**,struct ListNode**);

    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* result=NULL,*p1=l1,*p2=l2,*point;
    while(p1!=NULL || p2!=NULL)
    {

        if(p1==NULL)
        {
           while(p2!=NULL)
           {
               if(result==NULL)
               {
                   result=insert(p2->val);
                   point=result;
               }
               else
               {
                   result->next=insert(p2->val);
                   result=result->next;
               }
               p2=p2->next;
           }
        }
        else if(p2==NULL)
        {
           while(p1!=NULL)
           {
               if(result==NULL)
               {
                   result=insert(p1->val);
                   point=result;
               }
               else
               {
                   result->next=insert(p1->val);
                   result=result->next;
               }
               p1=p1->next;
           }
        }
        else
        {
            struct ListNode** tmp=min(&p1,&p2);
    
            if(result==NULL)
            {
               result=insert((*tmp)->val);
               point=result;
            }
            else
            {
               result->next=insert((*tmp)->val);
               result=result->next;
            }
            (*tmp)=(*tmp)->next;
        }
    
        
    }
    
    return point;
    

    }
    struct ListNode* insert(int val)
    {
    struct ListNode* p=malloc(sizeof(struct ListNode));
    p->val=val;
    p->next=0;
    return p;
    }
    struct ListNode** min(struct ListNode** l1,struct ListNode** l2)
    {
    return ((*l1)->val < (*l2)->val)?l1:l2;
    }


Log in to reply
 

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