WHY? runtime error


  • 0
    C

    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {

    if(l1==NULL||l2==NULL)
    return l1==NULL?l2:l1;
    struct ListNode*head,*p;
    if(l1->val>l2->val){head=l2,p=l2;l2=l2->next;}
    else {head=l1,p=l1; l1=l1->next;}
    while(l1!=NULL||l2!=NULL)
    {
        if(l1->val>l2->val)
        {
            p->next=l2;
            l2=l2->next;
            p=p->next;
        }
        else
        {
            p->next=l1;
            l1=l1->next;
            p=p->next;
        }
    }
    if(l1==NULL)
    {p->next=l2;}
    else
    {p->next=l1;}
    return head;
    

    }


  • 1
    Y

    Your while loop's condition should be:

    while (l1 != NULL && l2 != NULL)
    

    instead of:

    while (l1 != NULL || l2 != NULL)
    

    Otherwise, when either l1 or l2 is NULL, you will be dereferencing a NULL pointer for this line:

    if (l1->val > l2->val)

Log in to reply
 

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