开发者社区> 问答> 正文

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

展开
收起
a123456678 2016-03-20 14:26:01 2059 0
1 条回答
写回答
取消 提交回答
  • 链表没有终结.每次malloc后马上给新生出的节点的next赋NULL值就可以了.移动两个地方。

    l->next = NULL;

    p->next->next = NULL;

    2019-07-17 19:09:38
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载