/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* result = new ListNode(-1); //结果链表头结点
ListNode* cur = result; //当前结点
int sum = 0; //当前位数的和
bool carry = false; //进位
while (l1 || l2) {
sum = 0; //每次计算前都需将当前位数之和清零
if (l1) { //当前链表不为空时,便与sum进行相加
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
}
if (carry) { //进位
sum ++;
}
cur->next = new ListNode(sum % 10);
cur = cur->next;
if (sum >= 10)
carry = true;
else
carry = false;
}
if (carry) {
cur->next = new ListNode(1); //因为没有后续了,只有一个进位,便为1
}
return result->next; //result是头结点,真正的结果是从result->next开始
}
};
力扣002 大数相加
最新推荐文章于 2024-04-09 23:46:24 发布