ifidieyoung 2015-05-14 16:11 采纳率: 33.3%
浏览 2979
已采纳

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条回答 默认 最新

  • 知常曰明 2015-05-14 22:07
    关注

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

    l->next = NULL;
    

    p->next->next = NULL;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作