C++ stack solution


  • 0
    W

    class Solution {

    public:

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head = NULL;
        stack<int> st1;
        stack<int> st2;
        while (l1) {
            st1.push(l1->val);
            l1 = l1->next;
        }
        while (l2) {
            st2.push(l2->val);
            l2 = l2->next;
        }
        int carry = 0;
        
        while (!st1.empty() || !st2.empty() || carry) {
            int num1 = st1.empty() ? 0: st1.top();
            if (!st1.empty()) st1.pop();
            int num2 = st2.empty()? 0: st2.top();
            if (!st2.empty()) st2.pop();
            int sum = num1 + num2 + carry;
            
            ListNode *newNode = new ListNode(sum%10);
            //insert in front
            newNode->next = head;
            head = newNode;
            carry = sum/10;
            l1 = l1? l1->next:NULL;
            l2 = l2? l2->next: NULL;
        }
        return head;
    }
    

    };


Log in to reply
 

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