2. 两数相加

https://leetcode-cn.com/problems/add-two-numbers/description/

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例

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

主要思路:

思路很直接,直接采用双指针来实现,需要考虑进位的情况。


/**
 * 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 bonus = 0;
        ListNode* head = new(std::nothrow) ListNode(0);
        ListNode* curr = head;
        ListNode* next1 = l1;
        ListNode* next2 = l2;
        while (next1 != NULL || next2 != NULL) {
            int val1 = 0;
            if (next1 != NULL) {
                val1 = next1->val;
                next1 = next1->next;
            }

            int val2 = 0;
            if (next2 != NULL) {
                val2 = next2->val;
                next2 = next2->next;
            }

            int val = (val1 + val2 + bonus);
            ListNode* node = new(std::nothrow) ListNode(val % 10);
            curr->next = node;
            curr = node;
            bonus = val / 10;
        }

        if (bonus != 0) {
            ListNode* node = new(std::nothrow) ListNode(bonus);
            curr->next = node;
        }

        return head->next;
    }
};

你可能感兴趣的:(2. 两数相加)