[C] Runtime Error -- Need help


  • 0
    V

    Can somebody help me with this piece of code? It seems to be passing all the test cases I'm testing but when I submit it, it fails with the message:

    Runtime error
    Last executed input : [5]
                          [5]
    
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
       struct ListNode *head;
       struct ListNode *l3;
       
       int a = 0;
       int b = 0;
       int s = 0;
       int carry = 0;
       
       head = (struct ListNode *)malloc(sizeof(*head));
       l3 = head;
       l3->val = 0;
       l3->next = NULL;
       
       while(l1 != NULL || l2 != NULL || carry != 0){
           a = (l1 != NULL) ? l1->val : 0;
           b = (l2 != NULL) ? l2->val : 0;
           
           s = a + b + carry;
           if (s > 9){
               carry = s/10;
               l3->val = s%10;
           }
           else{
               l3->val = s;
               carry = 0;
           }
           l1 = (l1 != NULL) ? l1->next : NULL;
           l2 = (l2 != NULL) ? l2->next : NULL;
           
           if (l1 != NULL || l2 != NULL || carry != 0) {
               l3->next = (struct ListNode *)malloc(sizeof(*head));
               l3 = l3->next;
           }
           
       }
    
        return head;
    }
    

  • 0
    V

    In case anyone was wondering, I found the problem..

    In the creation of l3->next the values should be initialized..
    So the code should be

    if (l1 != NULL || l2 != NULL || carry != 0) {
               l3->next = (struct ListNode *)malloc(sizeof(*head));
               l3 = l3->next;
               l3->val = 0;
               l3->next = NULL;
           }
    

    The fact is that the program was running successfully on each test case and only when multiple test cases where run did the error occur.


Log in to reply
 

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