【LeetCode热题100】【链表】两数相加
基本思路同:【leetcode】大数相加-CSDN博客
数值的位置已经倒过来了,用一个进位记录进位,用一个数记录和,链表到空了就当成0
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *head = nullptr, *tail = nullptr;
int carry = 0;
while (l1 || l2 || carry) {
int a = l1 == nullptr ? 0 : l1->val;
int b = l2 == nullptr ? 0 : l2->val;
int sum = a + b + carry;
if (head == nullptr)
head = tail = new ListNode(sum % 10);
else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
carry = sum / 10;
if (l1)l1 = l1->next;
if (l2)l2 = l2->next;
}
return head;
}
};
原文地址:https://blog.csdn.net/weixin_62264287/article/details/137692253
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!