/**
* 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*p=l1;
ListNode*q=l2;
ListNode*head=new ListNode(0);
ListNode*curr=head;
int carry=0,x=0,y=0,sum=0;
while(p!=NULL||q!=NULL)//所给的节点不一定都一样长,所以当短的算完之后长的依旧需要计算
{
if(p!=NULL)
x=p->val;
else
x=0;//如果短的已经算完了,则不用再次计算,即置0
if(q!=NULL)
y=q->val;
else
y=0;
sum=x+y+carry;
carry=sum/10;
curr->next=new ListNode(sum%10);
curr=curr->next;
if(p!=NULL)
p=p->next;
if(q!=NULL)
q=q->next;
}
if(carry!=0)
curr->next=new ListNode(carry);
return head->next;
}
};