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
#include
#include
using namespace std;
//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 *pre=NULL;
ListNode *tmp=NULL;
ListNode *tmp1=l1;
ListNode *tmp2=l2;
int sum=0;
while( tmp1 != NULL && tmp2 != NULL )
{
sum= tmp1->val + tmp2->val + sum;
tmp=new ListNode(sum % 10 );
tmp->next=NULL;
sum = sum > 9 ? 1 : 0 ;
if(list==NULL)//只有第一次执行
{
list=tmp;
pre=list;
}
else
{
pre->next=tmp;
pre=tmp;
}
tmp1=tmp1->next;
tmp2=tmp2->next;
}
tmp1= (tmp1==NULL) ? tmp2 : tmp1;
while( tmp1 != NULL )
{
sum= tmp1->val + sum;
tmp=new ListNode(sum % 10 );
tmp->next=NULL;
sum = sum > 9 ? 1 : 0 ;
if(list==NULL)//只有第一次执行
{
list=tmp;
pre=list;
}
else
{
pre->next=tmp;
pre=tmp;
}
tmp1=tmp1->next;
}
if(sum)//最后有进位!!!!
{
tmp=new ListNode(sum % 10 );
tmp->next=NULL;
pre->next=tmp;
}
return list;
}
Solution():list(NULL){};
~Solution()
{
ListNode *tmp=list;
ListNode *tmp1=NULL;
while(tmp!=NULL)
{
tmp1=tmp;
tmp=tmp->next;
delete tmp1;
}
};
ListNode* list;
};
int main()
{
ListNode l1(5);
//ListNode l2(8);
//ListNode l3(3);
//ListNode l4(2);
//ListNode l5(2);
//l1.next=&l2;
//l2.next=&l3;
ListNode l6(5);
//ListNode l7(6);
//ListNode l8(4);
//l6.next=&l7;
//l7.next=&l8;
Solution sl;
ListNode *tmp=sl.addTwoNumbers(&l1,&l6);
while(tmp!=NULL)
{
cout<
val<<"-";
tmp=tmp->next;
}
sl.~Solution();
cout<
要注意最后一个有进位的情况,如输入【9】、【1】 结果应该是 0->1 不要把1丢了
提交代码的时候有析构函数,报错:runtime error,去掉析构函数就没问题了
代码优化
采用头结点的下一个作为返回,可以省去头结点为空的判断。
循环时只判断 或 而不是且 ,只要有一个不空就做累加,为空就用0代替,精简了代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null||l2==null)
return l1==null?l2:l1;
ListNode c1=l1;
ListNode c2=l2;
ListNode ret=new ListNode(0);//省去判断头结点为空
ListNode pre=ret;
int jw=0;
while(c1!=null || c2!=null){ // 不要用 && ,用 || ,如果有一个为空就用0来代替!!
int tmp1=c1==null?0:c1.val;
int tmp2=c2==null?0:c2.val;
int tmp=tmp1+tmp2+jw;
jw=tmp/10;
pre.next=new ListNode(tmp%10);
pre=pre.next;
if(c1!=null) c1=c1.next;
if(c2!=null) c2=c2.next;
}
if(jw!=0){
pre.next=new ListNode(jw);
}
return ret.next;
}
}