解法一:栈
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> s1,s2;
while (l1) {
s1.push(l1->val);
l1 =l1->next;
}
while(l2) {
s2.push(l2->val);
l2 = l2->next;
}
int carry =0;
ListNode* ans = nullptr;
while (!s1.empty() || (!s2.empty()) || carry!=0) {
if (!s1.empty()) {
carry += s1.top();
s1.pop();
}
if (!s2.empty()) {
carry += s2.top();
s2.pop();
}
auto cur_node = new ListNode(carry%10);
cur_node -> next =ans;
ans = cur_node;
carry = carry / 10;
}
return ans;
}
};
解法二:dfs
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int diff = size(l1)-size(l2);
l1 = new ListNode(0, l1);
l2 = new ListNode(0, l2);
if (diff<0) {
fillZero(l1, -diff);
} else {
fillZero(l2, diff);
}
dfs(l1, l2);
return l1->val==0?l1->next:l1;
}
int dfs(ListNode *l1, ListNode *l2) {
if (l1==nullptr) {
return 0;
}
int carry = dfs(l1->next, l2->next);
int sum = l1->val+l2->val+carry;
l1->val = sum % 10;
carry = sum / 10;
return carry;
}
int size(ListNode *l) {
int size = 0;
while (l != nullptr) {
size++;
l = l->next;
}
return size;
}
void fillZero(ListNode *l, int n) {
while (n > 0) {
n--;
ListNode* cur = new ListNode();
cur->next = l->next;
l->next = cur;
}
}
};