leetcode 题解 2. Add Two Numbers

来源:互联网 发布:周小帅私房菜淘宝店 编辑:程序博客网 时间:2024/05/16 08:56

leetcode的第二题,这一题实际上已经将问题做了简化,链表已经进行了逆序,因此只要从后向前处理即可。

这里有几点需要注意的问题:

两个数相加后结果可能大于10,因此需要主要进位的问题。

两个链表的长度可能不同,若一个链表为空,则将其值设为0。

若最后的结果仍然大于10,则还要再进一位。

直接将结果贴出来。

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {    if(l1==NULL) return l2;    if(l2==NULL) return l1;    int add = 0;    int sum = 0;    int tempSum = 0;    int l1val = 0;    int l2val = 0;    struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode));    struct ListNode* cur = result;    struct ListNode* nxt;    struct ListNode* pre;    while(l1!=NULL||l2!=NULL){        if(l1) l1val = l1->val;        else l1val = 0;        if(l2) l2val = l2->val;        else l2val = 0;        tempSum = l1val + l2val + add;        sum = tempSum%10;        add = tempSum/10;        cur->val = sum;        if(l1!=NULL) l1 = l1->next;        if(l2!=NULL) l2 = l2->next;        nxt = (struct ListNode*)malloc(sizeof(struct ListNode));        cur->next = nxt;        pre = cur;        cur = nxt;    }    if(add!=0){        cur->val = add;        pre = cur;    }    pre->next = NULL;    return result;    }


0 0