C++ Solution


  • 0
    W
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            stack<int> stack1, stack2;
            while (l1 || l2) {
                if (l1 != NULL) {
                    stack1.push(l1->val);
                    l1 = l1->next;
                }
                if (l2 != NULL) {
                    stack2.push(l2->val);
                    l2 = l2->next;
                }
            }
            int carry = 0;
            ListNode* ret = NULL;
            while (!stack1.empty() || !stack2.empty()) {
                int num1 = 0, num2 = 0;
                if (!stack1.empty()) {
                    num1 = stack1.top();
                    stack1.pop();
                }
                if (!stack2.empty()) {
                    num2 = stack2.top();
                    stack2.pop();
                }
                int sum=num1 + num2 + carry;
                ListNode *tmp=ret;
                ret = new ListNode(sum % 10);
                ret->next=tmp;
                carry=sum/10;
            }
            if (carry) {
                ListNode *tmp=ret;
                ret = new ListNode(carry);
                ret->next = tmp;
            }
            return ret;
        }
    };
    

Log in to reply
 

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