LC Hot 100 链表专题 - 2 两数相加
// 模拟数学计算即可,主要复用原链表空间,不要 new 空间,否则会超出内存限制。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1 == nullptr) return l2;
if(l2 == nullptr) return l1;
auto dummy = new ListNode(-1);
auto cur = dummy;
int num = 0;
while(l1 && l2) {
int n = (l1->val + l2->val + num) % 10;
num = (l1->val + l2->val + num) / 10;
l1->val = n;
auto next = l1->next;
cur->next = l1;
l1 = next;
l2 = l2->next;
cur = cur->next;
}
while(l1) {
int n = (l1->val + num) % 10;
num = (l1->val + num) / 10;
l1->val = n;
auto next = l1->next;
cur->next = l1;
l1 = next;
cur = cur->next;
}
while(l2) {
int n = (l2->val + num) % 10;
num = (l2->val + num) / 10;
l2->val = n;
auto next = l2->next;
cur->next = l2;
l2 = next;
cur = cur->next;
}
if (num != 0) {
auto ret = new ListNode(num);
cur->next = ret;
}
return dummy->next;
}
};