简体   繁体   中英

Runtime error while merging two sorted linked list

I am writing a c++ code to merge two sorted link lists.I am using two pointer method.I am getting a runtime error for the code below.I am unable to debug the code.

Error- Your submission stopped because of a runtime error. ex: division by zero, array index out of bounds, uncaught exception.

   /**
   * Definition for singly-linked list.
   * struct ListNode {
   *     int val;
   *     ListNode *next;
   *     ListNode(int x) : val(x), next(NULL) {}
   * };
   */
    ListNode* Solution::mergeTwoLists(ListNode* A, ListNode* B) {

    ListNode* head1=new ListNode(-1);
    head1->next=A;
    ListNode* head2=new ListNode(-1);
    head2->next=B;

    ListNode* temp1=head1;
    ListNode* temp2=head2;

    while(temp1->next!=NULL || temp2->next!=NULL)
    {
        if(temp1->next->val <= temp2->next->oval)
        {
           // if(temp1->next==NULL) break;
           //else
            temp1=temp1->next;
        }
        else if(temp1->next->val > temp2->next->oval)
        {
            ListNode* temp=temp1->next;
            ListNode* t2=temp2->next->next;
            temp1->next=temp2->next;
            temp2->next=t2;
            temp1->next->next=temp;
            temp1=temp1->next;
        }
    }
    if(temp1->next==NULL)
    {
    temp1->next=temp2->next;
    temp2->next=NULL;
    }
    return head1->next;
}

This condition:

while(temp1->next!=NULL || temp2->next!=NULL)

is incorrect, since you will be accessing invalid memory if exactly one of these pointers is NULL .

Instead, you need to do:

while(temp1->next!=NULL && temp2->next!=NULL)

Also, you should use nullptr instead of NULL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM