ifidieyoung
ifidieyoung
采纳率33.3%
2015-05-14 16:11

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条回答

  • gamefinity 知常曰明 6年前

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

    l->next = NULL;
    

    p->next->next = NULL;
    
    点赞 评论 复制链接分享

相关推荐