/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* Head = new ListNode(-1);
ListNode* pre = Head;
int carry=0,sum=0;
while(l1!=NULL || l2!=NULL || carry!=0){
if(l1!=NULL){
carry+=l1->val;
l1=l1->next;
}
if(l2!=NULL){
carry+=l2->val;
l2=l2->next;
}
ListNode* node=new ListNode(carry%10);
pre->next=node;
pre=node;
carry/=10;
}
return Head->next;
}
};
2. 两数相加/C++
最新推荐文章于 2023-05-27 13:18:12 发布