讨论/算法和数据结构/445. Add Two Numbers II 执行出错/
445. Add Two Numbers II 执行出错

两数相加 II 题目链接
代码如下:

int getListLen(struct ListNode *l)
{
    int len = 0;
    while(l)
    {
        len++;
        l = l->next;
    }
    return len;
}

int addHelper(struct ListNode *l_list, int l_len, struct ListNode *s_list, int s_len)
{
    if(l_len == 0 && s_len == 0)
        return 0;

    int carry = 0;
    if(l_len > s_len)
    {
        carry = addHelper(l_list->next, l_len -1, s_list, s_len);
        l_list->val = l_list->val + carry;
        carry = l_list->val / 10;
        l_list->val %= 10;
    }
    else
    {
        carry = addHelper(l_list->next, l_len - 1, s_list->next, s_len - 1);
        l_list->val = l_list->val + s_list->val + carry;
        carry = l_list->val / 10;
        l_list->val %= 10;
    }
    return carry;
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    if(l1 == NULL) return l2;
    if(l2 == NULL) return l1;

    int len1 = getListLen(l1), len2 = getListLen(l2);
    struct ListNode *head;
    int carry;
    if(l1 >= l2)
    {
        carry = addHelper(l1, len1, l2, len2);
        head = l1;
    }
    else
    {
        carry = addHelper(l2, len2, l1, len1);
        head = l2;
    }

    if(carry)
    {
        struct ListNode *tmp = (struct ListNode *)calloc(1, sizeof(struct ListNode));
        tmp->val = carry;
        tmp->next = head;
        head = tmp;
    }
    return head;
}

错误提示:
Line 36: Char 17: runtime error: member access within null pointer of type 'struct ListNode' (solution.c)
即使执行成功后,与代码逻辑也完全不符,更改测试用例输出结果感觉是固定的一个串。
但是在电脑上执行结果却是正确的,这个是因为啥呢?

展开讨论
375C发起于 2020-04-11

哪里用了个空指针吧?

第51行

if(l1 >= l2)

有问题吧,指针比大小是干什么?

这里改掉就过了