https://leetcode.com/problems/add-two-numbers-ii/description/
递归解:好处是,比自己写Stack快 不知道为啥。。。
class Solution {
public:
int countLen(ListNode* l) {
int ret = 0;
while (l) ret++, l = l->next;
return ret;
}
ListNode* add(ListNode* l1, ListNode* l2, int &carry) {
if (!l1 || !l2 ) return NULL;
carry = 0;
ListNode* tmp = add(l1->next, l2->next, carry);
int v = l1->val + l2->val + carry;
ListNode* now = new ListNode( v % 10 );
now->next = tmp;
carry = v/10;
return now;
}
ListNode* addcarry(ListNode* root, int &carry) {
if (!root) return NULL;
if (root->next)
root->next = addcarry(root->next, carry);
int v = root->val;
v += carry;
carry = v/10;
root->val = v % 10;
return root;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (!l2) return l1;
if (!l1) return l2;
int l1len = countLen(l1), l2len = countLen(l2);
if (l2len > l1len) swap(l1, l2), swap(l2len, l1len);
if (!l2len) return l1;
ListNode* newst = l1, *pre = NULL, *ret = NULL;
int diff = l1len - l2len, carry = 0;
while (diff-- ) {
// cout << "newst->" << newst->val << endl;
pre = newst;
newst = newst->next;
}
if (!pre) {
ret = add(l1, l2, carry);
if (carry) {
ListNode* tmp = new ListNode(carry);
tmp->next = ret;
return tmp;
} else {
return ret;
}
} else {
ret = add(newst, l2, carry);
if (carry) {
pre->next = NULL;
l1 = addcarry(l1, carry);
if (carry) {
ListNode* tmp = new ListNode(carry);
tmp->next = l1;
l1 = tmp;
}
}
pre->next = ret;
ret = l1;
return ret;
}
}
};
自己Stack,代码更清晰
class Solution {
public:
stack<int> tostack(ListNode* l1) {
stack<int> sta;
while (l1) {
sta.push(l1->val);
l1 = l1->next;
}
return sta;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (!l2) return l1;
if (!l1) return l2;
stack<int> sta1 = tostack(l1);
stack<int> sta2 = tostack(l2);
if (sta2.size() > sta1.size()) {
swap(l1, l2);
swap(sta2, sta1);
}
int carry = 0;
ListNode* ret = NULL, *tmp = NULL;
while (sta2.size()) {
int v = carry + sta2.top() + sta1.top();
carry = v/10;
v %= 10;
tmp = new ListNode(v);
tmp->next = ret;
ret = tmp;
sta2.pop();
sta1.pop();
}
while (sta1.size()) {
int v = sta1.top() + carry;
carry = v/10;
v %= 10;
tmp = new ListNode(v);
tmp->next = ret;
ret = tmp;
sta1.pop();
}
if (carry) {
tmp = new ListNode(carry);
tmp->next = ret;
ret = tmp;
}
return ret;
}
};