C++ solution using Stack


  • 0
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            stack<int> v1, v2;
            auto iter1 = l1, iter2 = l2;
            while(iter1){
                v1.push(iter1->val);
                iter1 = iter1->next;
            }
            while(iter2){
                v2.push(iter2->val);
                iter2 = iter2->next;
            }
            
            ListNode* head = new ListNode((v1.top()+v2.top())%10);
            int carry = (v1.top()+v2.top())/10;
            if(!v1.empty())v1.pop();
            if(!v2.empty())v2.pop();
            while( !v1.empty() || !v2.empty() ){
                int tmp = (!v1.empty() ? v1.top() : 0)+(!v2.empty() ? v2.top() : 0)+carry;
                ListNode* n = new ListNode(tmp%10);
                carry = tmp/10;
                if(!v1.empty())v1.pop();
                if(!v2.empty())v2.pop();
                n->next = head;
                head = n;
            }
            if( carry ) {
                ListNode* n = new ListNode(carry);
                n->next = head;
                head = n;
            }
            return head;
        }
    };
    

Log in to reply
 

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