Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
初始代码块(初学者水平)
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *header=NULL,*sum=NULL;
int carry=0;
bool flag=false;
while(l1!=NULL && l2!=NULL){
ListNode *tmp=new ListNode(0);
carry=l1->val+l2->val+flag;
if(carry>=10){
tmp->val = carry-10;
flag = true;
}
else{
tmp->val=carry;
flag=false;
}
if(!header)
header=tmp;
else
sum->next=tmp;
sum=tmp;
l1=l1->next;
l2=l2->next;
}
ListNode *last;
if(l1==NULL)
last=l2;
else
last=l1;
carry=0;
while(last!=NULL){
ListNode *tmp=new ListNode(0);
carry=last->val+flag;
if(carry>=10){
tmp->val=carry-10;
flag=true;
}
else{
tmp->val=carry;
flag=false;
}
sum->next=tmp;
sum=tmp;
last=last->next;
}
if(flag){
ListNode *tmp=new ListNode(0);
tmp->val=flag;
sum->next=tmp;
}
return header;
}
}
经过优化和学弟提醒之后
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *header=NULL,*sum=NULL;
int carry=0;
while(l1 || l2){
new ListNode(0);
if(l1) carry+=l1->val;
if(l2) carry+=l2->val;
ListNode *tmp=new ListNode(carry%10);
if(!header)
header=tmp;
else
sum->next=tmp;
carry/=10;
sum=tmp;
if(l1) l1=l1->next;
if(l2) l2=l2->next;
}
if(carry){
ListNode *tmp=new ListNode(carry);
sum->next=tmp;
}
return header;
}
我太悲伤了,第二个代码块是我奋斗的目标!