两数相加-链表

两数相加-链表

问题简述

数字倒序存储
1-2-3
						0-5-4     即(321+129 = 450)
9-2-1

代码

非递归实现
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *root = new ListNode(-1);
        ListNode *cursor = root;
        int carry = 0;
        while(l1 != nullptr || l2 != nullptr || carry != 0)
        {
            int l1val = l1 != nullptr? l1->val : 0;
            int l2val = l2 != nullptr? l2->val : 0;
            int sumval = l1val + l2val + carry;
            carry = (sumval) / 10;
            ListNode *sumNode = new ListNode(sumval % 10);
            sumNode->next = nullptr;
            cursor->next = sumNode;
            cursor = sumNode;

            if(l1 != nullptr)
                l1 = l1->next;
            if(l2 != nullptr)
                l2 = l2->next;
        }
        return root->next;
    }
};
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:白松林 返回首页