/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
stack<ListNode*> getstack(ListNode* head) {
stack<ListNode*> s;
while (head) {
s.push(head);
head = head->next;
}
return s;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
if (head1 == nullptr) return head2;
if (head2 == nullptr) return head1;
if (!head1 && !head2) return nullptr;
stack<ListNode*> s1 = getstack(head1);
stack<ListNode*> s2 = getstack(head2);
int carry = 0;
ListNode* node = new ListNode(0);
while (!s1.empty() || !s2.empty() || carry) {
int num1 = s1.empty() ? 0 : s1.top()->val;
int num2 = s2.empty() ? 0 : s2.top()->val;
if (!s1.empty()) s1.pop();
if (!s2.empty()) s2.pop();
int sum = num1 + num2 + carry;
carry = sum / 10;
ListNode* dummy = new ListNode(sum % 10);
dummy->next=node->next;
node->next=dummy;
}
return node->next;
}
};