C++_Using Stack


  • 0
    class Solution {
    public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        stack<int> s1;
        stack<int> s2;
        stack<int> s3;
        while(l1){
            s1.push(l1->val);
            l1 = l1->next;
        }
        while(l2){
            s2.push(l2->val);
            l2 = l2->next;
        }
        int carry = 0;
        while(!s1.empty() || !s2.empty()){
            int sum = carry;
            if(!s1.empty()){sum += s1.top(); s1.pop();}
            if(!s2.empty()){sum += s2.top(); s2.pop();}
            carry = sum/10;
            s3.push(sum%10);
        }
        if(carry) s3.push(carry);
        ListNode* root = new ListNode(0);
        ListNode* p = root;
        while(!s3.empty()){
            ListNode* tmp = new ListNode(s3.top());
            p->next = tmp;
            p = p->next;
            s3.pop();
        }
        return root->next;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.