题目链接:https://leetcode-cn.com/problems/add-two-numbers/
题目如下:
/**
* 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) {
auto p1=l1,p2=l2;
ListNode* result=new ListNode(),*p=result;
int carry=0,sum=0;
while(p1!=NULL||p2!=NULL||carry==1){
if(p1&&p2){
sum=p1->val+p2->val;
p1=p1->next;
p2=p2->next;
}else if(p1==NULL&&p2!=NULL){
sum+=p2->val;
p2=p2->next;
}else if(p1!=NULL&&p2==NULL){
sum+=p1->val;
p1=p1->next;
}
if(carry==1){sum+=1;carry=0;}
ListNode* node=new ListNode(sum%10);
result->next=node;
result=node;
carry=sum/10;
sum=0;
}
return p->next;
}
};