/**
* 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* dummy=new ListNode();
ListNode* cur=dummy;
int carry=0;
while(l1!=nullptr||l2!=nullptr){
int x=l1?l1->val:0;
int y=l2?l2->val:0;
int sum=x+y+carry;
cur->next=new ListNode(sum%10);
carry=sum/10;
if(l1) l1=l1->next;
if(l2) l2=l2->next;
cur=cur->next;
}
if(carry>0){
cur->next=new ListNode(carry);
}
return dummy->next;
}
};
【leetcode】2. 两数相加
最新推荐文章于 2024-06-24 16:57:17 发布