/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
bool adding=0;
ListNode yang(-1);
//ListNode yang1(-1);
//ListNode yang2(-1);
ListNode *h=&yang;
//ListNode *h1=&yang1;
//ListNode *h2=&yang2;
//h->next=l1;
//h1->next=l1;
//h2->next=l2;
int temp;
//if(len2>len1)swap(l1,l2);
int value2,value1;
/*for(int i=0;i<len1-1;i++)
{
if(l2!=NULL)
value2=l2->val;
else
value2=0;
if(adding)
{temp=l1->val+value2+1;adding=0;}
else
temp=l1->val+value2;
if(temp>=10)
{temp=temp-10;adding=1;}
l1->val=temp;
l1=l1->next;
}*/
while(l1!=NULL||l2!=NULL)
{
if(l1==NULL){value1=0;value2=l2->val;l2=l2->next;}
else if(l2==NULL){value2=0;value1=l1->val;l1=l1->next;}
else
{
value2=l2->val;l2=l2->next;
value1=l1->val;l1=l1->next;
}
if(adding)
{temp=value1+value2+1;adding=0;}
else
temp=value1+value2;
if(temp>=10)
{temp=temp-10;adding=1;}
h->next=new ListNode(temp);
h=h->next;
}
if(adding)
h->next=new ListNode(1);
return yang.next;
}
};
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//一开始想更改l1链表中的每个值,最后return l1,但是貌似链表的值无法用node->val=number直接修改
//最后就相当于一个一个开通一个ListNode的空间,存入得到的每个位的数
class Solution {public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
bool adding=0;
ListNode yang(-1);
//ListNode yang1(-1);
//ListNode yang2(-1);
ListNode *h=&yang;
//ListNode *h1=&yang1;
//ListNode *h2=&yang2;
//h->next=l1;
//h1->next=l1;
//h2->next=l2;
int temp;
//if(len2>len1)swap(l1,l2);
int value2,value1;
/*for(int i=0;i<len1-1;i++)
{
if(l2!=NULL)
value2=l2->val;
else
value2=0;
if(adding)
{temp=l1->val+value2+1;adding=0;}
else
temp=l1->val+value2;
if(temp>=10)
{temp=temp-10;adding=1;}
l1->val=temp;
l1=l1->next;
}*/
while(l1!=NULL||l2!=NULL)
{
if(l1==NULL){value1=0;value2=l2->val;l2=l2->next;}
else if(l2==NULL){value2=0;value1=l1->val;l1=l1->next;}
else
{
value2=l2->val;l2=l2->next;
value1=l1->val;l1=l1->next;
}
if(adding)
{temp=value1+value2+1;adding=0;}
else
temp=value1+value2;
if(temp>=10)
{temp=temp-10;adding=1;}
h->next=new ListNode(temp);
h=h->next;
}
if(adding)
h->next=new ListNode(1);
return yang.next;
}
};