LeetCode 445. 两数相加 II Add Two Numbers II (Medium)

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

 

来源:力扣(LeetCode)

/**
 * 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) {

        ListNode* head = nullptr;
        stack<int> stack1;
        stack<int> stack2;
        while (l1 != nullptr)
        {
            stack1.push(l1->val);
            l1 = l1->next;
        }
            
        while (l2 != nullptr)
        {
            stack2.push(l2->val);
            l2 = l2->next;
        }
        
        int carry = 0;
        while (!stack1.empty() || !stack2.empty() || carry != 0)
        {
            int sum = carry;
            if (!stack1.empty())
            {
                sum += stack1.top(); 
                stack1.pop();
            }
            if (!stack2.empty())
            {
                sum += stack2.top(); 
                stack2.pop();
            }
            //头插法
            //新节点链接到链表头部,然后新的节点成为新的头部
            ListNode* pNode = new ListNode(sum % 10);
            pNode->next = head;
            head = pNode;
            carry = sum / 10;
        }
        return head;
    }
};

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12903020.html
今日推荐