C++ runtime error. Could anyone help me to figure it out?


  • 0
    N
    class Solution {public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode preheader(-1), *p = &preheader;
         if ( !l1 ) return l2;
         if ( !l2 ) return l1;
         while( l1 || l2 ){
         if ( l2 -> val < l1 -> val )
         { //p -> next = new ListNode(l2 -> val);
          p -> next = l2;
           l2? l2 = l2 -> next:0;
             p = p -> next;
         }
           else {
             //  p -> next = new ListNode(l1 -> val);
             p -> next= l1;
               l1?l1 = l1 -> next:0;
               p = p -> next;
           }
         }
         return preheader.next;
    }};

  • 0
    N

    It says runtime error, but I have no idea how to deal with it.


  • 0
    D
    while( l1 || l2 ){
         if ( l2 -> val < l1 -> val )
    

    here l1 or l2 might be null.


  • 0
    N

    Thanks for you answer!! It make sense!


  • 0
    S

    while( l1 || l2 ) should be while(l1 && l2)


Log in to reply
 

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