leetcode2(两数相加)--C语言实现

 ̄綄美尐妖づ 提交于 2020-03-11 17:37:07

求:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

 

解:

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
     struct ListNode* resultList = (struct ListNode*)malloc(sizeof(struct ListNode));
     struct ListNode* currentNode = resultList;
     int x,y;
     int carry = 0;
     while(l1!=NULL || l2!=NULL){
        if(l1==NULL){
           x=0;
        }else{
           x=l1->val;
           l1=l1->next;
        }
        if(l2==NULL){
           y=0;
        }else{
           y=l2->val;
           l2=l2->next;
        }
        struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newNode->val = x+y+carry;
        newNode->next = NULL;
        currentNode->next = newNode;
        currentNode = newNode;
        if(newNode->val>=10){
            newNode->val-=10;
            carry = 1;
        }else{
            carry = 0;
        }
     }
     if(carry){
        struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newNode->val=1;
        newNode->next=NULL;
        currentNode->next = newNode;
     }
     return resultList->next;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!