[LeetCode#2][C]Add Two Numbers

题目如下:

这里写图片描述

思路:

其实就是基本的链表操作,只要注意进位的判断就好。

代码:

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* l3=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* cur=l3;             //指向当前结点
    int carry=0;                         //进位
    while(l1!=NULL||l2!=NULL)
    {
        int sum=0,a,b;
        a=(l1!=NULL)?l1->val:0;
        b=(l2!=NULL)?l2->val:0;
        sum=a+b+carry;
        carry=sum/10;
        cur->next=(struct ListNode*)malloc(sizeof(struct ListNode));
        cur=cur->next;
        cur->val=sum%10;
        if(l1!=NULL)
            l1=l1->next;
        if(l2!=NULL)
            l2=l2->next;
    }
    if(carry>0)                        //链表结束后是否还有进位
    {
        cur->next=(struct ListNode*)malloc(sizeof(struct ListNode));
        cur=cur->next;
        cur->val=carry;
    }
    cur->next=NULL;                   //注意细节
    return l3->next;
}

结果:

你可能感兴趣的:(链表,C语言,两数求和,LeetNode)