445. Add Two Numbers II(Leetcode每日一题-2020.04.14)

Problem

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

Solution

不翻转链表的情况下,可以将两个链表的节点值分别压入两个栈中。
出栈过程中,进行求和,并将结果压入第三个栈中。
第三个出栈过程中,构建结果链表。

/**
 * 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) {
        if(!l1 && !l2)
            return NULL;
        else if(!l1 && l2)
            return l2;
        else if(l1 && !l2)
            return l1;
        
        stack<int> l1_stack;
        stack<int> l2_stack;

        ListNode *cur = l1;
        while(cur)
        {
            l1_stack.push(cur->val);
            cur = cur->next;
        }

        cur = l2;
        while(cur)
        {
            l2_stack.push(cur->val);
            cur = cur->next;
        }

        int carry = 0;
        

        stack<int> res_stack;
        while(!l1_stack.empty() || !l2_stack.empty() || carry != 0)
        {
            int l1_val = l1_stack.empty()?0:l1_stack.top();
            if(!l1_stack.empty())
            {
                l1_stack.pop();
            }

            int l2_val = l2_stack.empty()?0:l2_stack.top();
            if(!l2_stack.empty())
            {
                l2_stack.pop();
            }

            int sum = l1_val + l2_val + carry;

            res_stack.push(sum % 10);

            carry = sum / 10;
        }

        ListNode * dummy = new ListNode(0);
        cur = dummy;
        while(!res_stack.empty())
        {
            cur->next = new ListNode(res_stack.top());
            res_stack.pop();
            cur = cur->next;
        }

        return dummy->next;

    }
};
发布了547 篇原创文章 · 获赞 217 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105523426