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
思路
很简单,按照顺序相加就行,注意进位。这个题目有两点比较坑爹:1、reverse order到底是什么顺序?举得例子刚好又完全看不出来顺序
。2、返回指针?貌似还没怎么看到过,我一直在纠结他是要自己delete?不然怎么返回指针?实践证明,果然是他自己delete,这太不符合程序员的逻辑了。
![尴尬](http://static.blog.csdn.net/xheditor/xheditor_emot/default/awkward.gif)
这道题应该考察的就是各种指针操作,赋值顺序啥的。
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ListNode *a,*b,*res,*p;
int pover=0,over=0;
if(l1==NULL && l2==NULL) {
ListNode *tmp=new ListNode(0);
return tmp;
}else if(l1==NULL && l2!=NULL){
return l2;
}else if(l1!=NULL && l2==NULL){
return l1;
}else{
int s=l1->val+l2->val;
if(s>=10){
pover=1;
s-=10;
}else over=0;
ListNode *tmp=new ListNode(s);
res=tmp;
p=tmp;
}
a=l1->next;b=l2->next;
while(true){
if(a==NULL && b==NULL){
if(pover==1){
ListNode *tmp=new ListNode(1);
p->next=tmp;
p=p->next;
}
break;
}else if(a!=NULL && b==NULL){
int s=a->val+pover;
if(s>=10){
over=1;
s-=10;
}else over=0;
ListNode *tmp=new ListNode(s);
p->next=tmp;
p=p->next;
pover=over;
}else if(a==NULL && b!=NULL){
int s=b->val+pover;
if(s>=10){
over=1;
s-=10;
}else over=0;
ListNode *tmp=new ListNode(s);
p->next=tmp;
p=p->next;
pover=over;
}else{
int s=a->val+b->val+pover;
if(s>=10){
over=1;
s-=10;
}else over=0;
ListNode *tmp=new ListNode(s);
p->next=tmp;
p=p->next;
pover=over;
}
if(a!=NULL) a=a->next;
if(b!=NULL) b=b->next;
}
return res;
}
};