原题链接:Leecode 2. 两数相加
/**
* 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) {
int tmp=0,n=0;
ListNode* root=nullptr;
ListNode* pre=nullptr;
ListNode* now=nullptr;
while(l1 || l2)
{
tmp=0;
if(l1) tmp+=l1->val;
if(l2) tmp+=l2->val;
now=new ListNode((tmp+n)%10);
n=(tmp+n)/10;
if(!root)
{root=now;pre=now;}
else
{pre->next=now;pre=now;}
if(l1) l1=l1->next;
if(l2) l2=l2->next;
}
if(n>0)
pre->next=new ListNode(n);//如果最后还有进位
return root;
}
};