没什么好说的,只要考虑全面即可~~~
/**
* 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) {
int cc=0;
ListNode *ans=NULL,*temp=NULL,*now=NULL;
bool isfirst=true;
int i;
while(!(l1==NULL && l2==NULL))
{
if(l1==NULL)
{
if(isfirst)
{
temp=new ListNode(l2->val+cc);
now=temp;
ans=now;
isfirst=false;
l2=l2->next;
cc=0;
}
else
{
temp=new ListNode((l2->val+cc)%10);
cc=(l2->val+cc)/10;
now->next=temp;
now=temp;
l2=l2->next;
}
}
else if(l2==NULL)
{
if(isfirst)
{
temp=new ListNode(l1->val+cc);
now=temp;
ans=now;
isfirst=false;
l1=l1->next;
cc=0;
}
else
{
temp=new ListNode((l1->val+cc)%10);
cc=(l1->val+cc)/10;
now->next=temp;
now=temp;
l1=l1->next;
}
}
else
{
if(isfirst)
{
temp=new ListNode((l2->val+l1->val+cc)%10);
cc=(l1->val+l2->val+cc)/10;
now=temp;
ans=now;
isfirst=false;
l1=l1->next;
l2=l2->next;
}
else
{
temp=new ListNode((l2->val+l1->val+cc)%10);
cc=(l1->val+l2->val+cc)/10;
now->next=temp;
now=temp;
l1=l1->next;
l2=l2->next;
}
}
}
if(cc!=0)
{
temp=new ListNode(cc);
now->next=temp;
}
return ans;
}
};