/**
* 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 *Dummyhead = new ListNode(0);
ListNode *mov = Dummyhead;
ListNode *p1 = l1,*p2 = l2;
int carry = 0,sum;
int num1,num2;
while(p1 != nullptr || p2 != nullptr)
{
num1 = (p1 == nullptr) ? 0 : p1 -> val;
num2 = (p2 == nullptr) ? 0 : p2 -> val;
sum = num1 + num2 + carry;
mov -> next = new ListNode(sum % 10);
carry = sum / 10;
mov = mov -> next;
if(p1 != nullptr)p1 = p1 -> next;
if(p2 != nullptr)p2 = p2 -> next;
}
if(carry)
{
mov -> next = new ListNode(carry);
mov = mov -> next;
mov -> next = nullptr;
}
return Dummyhead -> next;
}
};
力扣刷题 3.两数相加——中等题
最新推荐文章于 2024-09-26 12:00:11 发布