** 445 两数相加

我的方法,太繁琐

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    if (l1 == nullptr || l2 == nullptr) {
        if (l1 == nullptr)
            return l2;
        return l1;
    }
    stack<ListNode *> stack1, stack2;
    for (ListNode *t1=l1; t1; stack1.push(t1), t1 = t1->next);
    for (ListNode *t2=l2; t2; stack2.push(t2), t2 = t2->next);
    int carry = 0;
    while (!stack1.empty() && !stack2.empty()) {
        stack1.top()->val += (stack2.top()->val + carry);
        if (stack1.top()->val >= 10) {
            carry = 1;
            stack1.top()->val %= 10;
        } else
            carry = 0;
        stack1.pop();
        stack2.pop();
    }
    if (!stack2.empty()) {
        stack2.top()->next = l1;
        while (carry && !stack2.empty()) {
            stack2.top()->val += 1;
            if (stack2.top()->val == 10) {
                carry = 1;
                stack2.top()->val = 0;
            } else
                carry = 0;
            stack2.pop();
        }
        if (carry) {
            auto *t1 = new ListNode(1);
            t1->next = l2;
            l2 = t1;
        }
        return l2;
    } else if (!stack1.empty()) {
        while (carry && !stack1.empty()) {
            stack1.top()->val += 1;
            if (stack1.top()->val == 10) {
                carry = 1;
                stack1.top()->val = 0;
            } else
                carry = 0;
            stack1.pop();
        }
        if (carry) {
            auto *t1 = new ListNode(1);
            t1->next = l1;
            l1 = t1;
        }
        return l1;
    } else {
        if (carry) {
            auto *t1 = new ListNode(1);
            t1->next = l1;
            l1 = t1;
        }
        return l1;
    }
}

简洁

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        stack<int> s1, s2; // store digits in stack
        for (; l1; l1 = l1->next) s1.push(l1->val); 
        for (; l2; l2 = l2->next) s2.push(l2->val);
        
        ListNode *res = new ListNode(0), *tmp = NULL;
        for (int sum = 0; !s1.empty()||!s2.empty(); tmp = new ListNode(sum/=10), tmp->next = res, res = tmp) {
            if (!s1.empty()) sum += s1.top(), s1.pop(); // get digit sum
            if (!s2.empty()) sum += s2.top(), s2.pop();
            res->val = sum%10;
        }
        return res->val? res : res->next;        
    }
原文地址:https://www.cnblogs.com/INnoVationv2/p/10261687.html