ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if (l1->next == nullptr && l1->val == 0)
return l2;
else if (l2->next == nullptr && l2->val == 0)
return l1;
int carry = 0;
ListNode head(0), *temp = &head;
while (l1 != nullptr && l2 != nullptr) {
l1->val = l1->val + l2->val + carry;
if (l1->val > 9) {
carry = 1;
l1->val %= 10;
} else
carry = 0;
temp->next = l1;
temp = temp->next;
l1 = l1->next;
l2 = l2->next;
}
if (carry) {
ListNode *it = (l1 != nullptr) ? l1 : l2 != nullptr ? l2 : nullptr;
if (it != nullptr) {
while (true) {
it->val += carry;
temp->next = it;
temp=temp->next;
if (it->val == 10) {
carry = 1;
it->val = 0;
if (it->next != nullptr)
it = it->next;
else {
temp->next = new ListNode(1);
break;
}
} else
break;
}
} else
temp->next = new ListNode(1);
} else
temp->next = (l1 != nullptr) ? l1 : l2 != nullptr ? l2 : nullptr;
return head.next;
}