2. 两数相加

模拟。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head = nullptr, *tail = nullptr;
        int carry = 0;  // 进位
        while(l1 || l2 || carry)
        {
            int t = carry;
            if(l1) t += l1->val, l1 = l1->next;
            if(l2) t += l2->val, l2 = l2->next;
            ListNode* node = new ListNode(t % 10);
            if(!tail) head = tail = node;
            else tail->next = node, tail = node;
            carry = t / 10;
        }

        return head;
    }
};
posted @ 2021-06-23 11:42  Dazzling!  阅读(17)  评论(0编辑  收藏  举报