How come my C solution have runtime error Add Two Numbers


  • 0
    T

    I tested it extensively on my own, all work as expected.
    Runtime error on Last executed input:
    [1,1,0,4,7,2,7,3,0,1], [2,5,5,6,8,0,3,0,5,1].
    I specificly tested this case as well.

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* ret_num;
    int carry = 0;
    int first = 1;
    struct ListNode* last_node;
    while(l1 != NULL || l2 != NULL || carry > 0){
      struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
      if(first){
        ret_num = new_node;
        last_node = new_node;
        first = 0;
      }else{
        last_node->next = new_node;
        last_node = new_node;
      }
      int l1_val = (l1 != NULL) ? l1->val : 0;
      int l2_val = (l2 != NULL) ? l2->val : 0;
      new_node->val = l1_val + l2_val + carry;
      carry = (new_node->val)/10;
      new_node->val = (new_node->val)%10;
      l1 = (l1 != NULL) ? l1->next : l1;
      l2 = (l2 != NULL) ? l2->next : l2;
    }
    return ret_num;
    }

  • 1
    G

    new_node->next is not assigned. what you did is "last_node->next = new_node;". So at the end of the linked list, the next pointer is not assigned and undefined.

    I suggest you assigned next pointer as NULL after malloc.


Log in to reply
 

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