leetcode 002 add two numbers C语言
 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) 
{
    struct ListNode *l, *p;
    l = (struct ListNode*)malloc(sizeof(struct ListNode));
    l->val = l1->val + l2->val;
    p = l;
    l1 = l1->next;
    l2 = l2->next;
    while(l1||l2||p->val>9)
    {
        p->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        p->next->val = p->val/10;
        p->val %= 10;
        p = p->next;

        if(l1) 
        {
            p->val += l1->val;
            l1 = l1->next;
        }
         if(l2) 
        {
            p->val += l2->val;
            l2 = l2->next;
        }
    }
    return l;
}

请问这样有错吗?我自己反复看了觉得没有问题啊,原题 如下
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

1个回答

链表没有终结.每次malloc后马上给新生出的节点的next赋NULL值就可以了.移动两个地方。

l->next = NULL;

p->next->next = NULL;
ifidieyoung
ifidieyoung 原来是这样,非常感谢
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问