ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int t = 0, a = 0, b = 0;
ListNode *l3 = nullptr, *tail = nullptr;
while (l1 || l2) {
a = l1?l1->val:0;
b = l2?l2->val:0;
t = a + b + t;
if (l3 == nullptr) {
l3 = tail = new ListNode(t % 10);
} else {
tail->next = new ListNode(t % 10);
tail = tail->next;
}
t = t / 10;
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
if (t > 0) {
tail->next = new ListNode(t);
}
return l3;
}
网友评论