解题思路:
\qquad
这道题可以用模拟很直观的解决,模式加法的计算过程,只不过套了一层链表的外衣。题目给出的数字在链表中是按照逆序排列的,即链表头节点的值代表相加数字的个位,这样只需要从链表头开始计算加法即可得到最终的结果。
\qquad
加法的计算可以用以下过程概括:value = (a + b + carry) % 10
;
carry = value / 10
。需要注意的是,最后遍历完两个链表之后,如果carry
不为0,需要进位,需要额外在末尾添加一个节点。
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = nullptr;
ListNode* curr = nullptr;
int carry = 0, value = 0;
while(l1 != nullptr || l2 != nullptr)
{
if(l1 != nullptr && l2 != nullptr)
{
value = l1->val + l2->val + carry;
l1 = l1->next;
l2 = l2->next;
}
else if(l1 != nullptr)
{
value = l1->val + carry;
l1 = l1->next;
}
else
{
value = l2->val + carry;
l2 = l2->next;
}
carry = value / 10;
value = value % 10;
ListNode* node = new ListNode(value, nullptr);
if(curr == nullptr)
{
curr = node;
head = curr;
}
else
{
curr->next = node;
curr = curr->next;
}
}
if(carry != 0)
{
curr->next = new ListNode(carry, nullptr);
}
return head;
}