Who can tell me the reason why always run time error?


  • 0
    L

    /**

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

    class Solution {
    public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *p1 = l1;
    ListNode *p2 = l2;
    ListNode *start = NULL;

        if(!(p1&&p2)){
            if(!p1 && p2)
            return reverseListNode(p2);
            else if(p1 && !p2)
            return reverseListNode(p1);
            else
            return NULL;
        }
         
        while(p1&&p2){
            p1 = p1->next;
            p2 = p2->next;
            
        }
            p1=l1;
            p2=l2;
        if(!p1){
            
            while(!p1){
                p2->val = (p2->val+p1->val)%10;
            }
            
            return start = reverseListNode(p2);
        }
        else{
            while(!p2){
               p1->val= (p1->val+p2->val)%10; 
            }
            return start = reverseListNode(p1);
        }
        
        
    }
    

    ListNode* reverseListNode(ListNode l){
    ListNode
    l1 = l;
    ListNode* l2 = NULL;

     ListNode* tmp = NULL;
     
     ListNode *head = NULL;
     
     
     if(!l1)
     return l1;
     else{
         head->next = NULL;
         
         while(l1){
             tmp = head->next;
             l2 = l1;
             l1=l1->next;
             head->next=l2;
             l2->next = head->next;
             
         }
         return head->next;
     }
    

    }
    };


  • 0
    M

    ListNode* reverseListNode(ListNode l){ ListNode l1 = l; ListNode* l2 = NULL;

    ListNode* tmp = NULL;

    ListNode *head = NULL; /// here head is a Null pointer

    if(!l1)
    return l1;
    else{
    head->next = NULL; ///how can you access an head->next with the null head point ?

     while(l1){
         tmp = head->next;
         l2 = l1;
         l1=l1->next;
         head->next=l2;       /// here should be the head = l2
         l2->next = head->next;
    
     }
     return head->next;
    

    }


Log in to reply
 

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