LeetCode445. 两数相加 II

题目

分析

用栈存储,并进行模拟。采用头插

代码

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        stack<int>s1;stack<int>s2;
        while(l1){
            s1.push(l1->val);
            l1 = l1->next;
        }
        while(l2){
            s2.push(l2->val);
            l2 = l2->next;
        }
        ListNode *head = new ListNode(); //创建哑节点
        int sum = 0;
        while(!s1.empty() || !s2.empty() || sum){
            sum += s1.empty() ? 0 : s1.top();
            sum += s2.empty() ? 0 : s2.top();
            if(!s1.empty()) s1.pop();
            if(!s2.empty()) s2.pop();
            ListNode *node = new ListNode (sum % 10);
            sum /= 10;
            node->next = head->next;
            head->next = node;
        }
        return head->next;
    }
};

 

posted @ 2021-03-19 21:29  Uitachi  阅读(28)  评论(0)    收藏  举报