/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode *reverseList(ListNode *head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode *l = head, *r = l->next;
l->next = nullptr;
while (r) {
ListNode *t = r->next;
r->next = l;
l = r;
r = t;
}
return l;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
if (head1 == nullptr) return head2;
if (head2 == nullptr) return head1;
ListNode *l1 = reverseList(head1);
ListNode *l2 = reverseList(head2);
ListNode *ans = new ListNode(0), *cur = ans;
int carry = 0;
while (l1 || l2 || carry) {
int x = l1 ? l1->val : 0;
int y = l2 ? l2->val : 0;
int sum = x + y + carry;
carry = sum / 10;
sum %= 10;
cur->next = new ListNode(sum);
cur = cur->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
ans = ans->next;
ans = reverseList(ans);
return ans;
}
};