add-two-numbers

题目链接

add-two-numbers

题目内容

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例

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

解题思路

1.新建一个只有一个空节点的链表;;
2.设置一个进位标志;
3.设置一个循环,循环的结束标志是两个两个链表为空;
4.每次循环的动作是l1 + l2 + carry,结果大于10时,进位置1,结果减10,结果如果小于10,进位置0,结果存进新链表;

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode *l = new ListNode(-1);
        ListNode *tail = l;
        while(l1 && l2)
        {
            ListNode *temp = new ListNode;
            temp->val = l1->val + l2->val + carry;
            if(temp->val > 9)
            {
                temp->val = temp->val - 10;
                carry = 1;
            }
            else
                carry = 0;
            tail->next = temp;
            tail = tail->next;
            l1 = l1->next;
            l2 = l2->next;
        }
        if(l1)
        {
            while(l1)
            {
                ListNode *temp = new ListNode;
                temp->val = l1->val + carry;
                if(temp->val > 9)
                {
                    temp->val = temp->val - 10;
                    carry = 1;
                }
                else
                    carry = 0;
                tail->next = temp;
                tail = tail->next;
                l1 = l1->next;
            }
        }
        if(l2)
        {
            while(l2)
            {
                ListNode *temp = new ListNode;
                temp->val = l2->val + carry;
                if(temp->val > 9)
                {
                    temp->val = temp->val - 10;
                    carry = 1;
                }
                else
                    carry = 0;
                tail->next = temp;
                tail = tail->next;
                l2 = l2->next;
            }
        }
        if(carry == 1)
        {
            ListNode *temp = new ListNode;
            temp->val = carry;
            tail->next = temp;
            tail = tail->next;
            tail->next = NULL;
        }
        return l->next;
    }
};
posted @ 2020-11-27 23:01  位军营  阅读(61)  评论(1编辑  收藏  举报