C++ Weird Runtime Error


  • 0
    S
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if(l1 == NULL) return l2;
            if(l2 == NULL) return l1;
            ListNode* tmp;
            ListNode* a = l1;
            ListNode* b = l2;
            while(a && b){
                //cout << a->val << " " << b->val << endl;
                if(a->val < b->val){
                    tmp->next = a;
                    tmp = a;
                    a=a->next;
                }else{
                    tmp->next = b;
                    tmp = b;
                    b=b->next;
                }
            }
            if(a) ans->next = a;
            if(b) ans->next = b;
            if(l1->val < l2->val) return l1;
            return l2;
        }
    };
    

    This will get a run time error on case:
    [-17,5,19,19]
    [-30,-29,-28,-28,-27,-26,-26,-23,-23,-21,-18,-18,-17,-15,-14,-13,-13,-8,-8,-7,-7,-4,-2,0,1,5,5,5,7,11,13,13,15,17,17,26,26,27,28]

    But when I uncomment the //cout << a->val << " " << b->val << endl; line, it's accepted...

    Anyone knows why?


  • 0
    S

    Oh, I got it, ListNode* tmp; should be ListNode* tmp = new ListNode(0);
    Otherwise when first encounter tmp->next = a; , tmp may be NULL or some dirty value;


Log in to reply
 

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