CC12:链式A+B
题目
有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}
解法
个位排在链表首部,进位就可以一位一位的来。要注意的一个是进位问题,另一个是可能位数不匹配的问题。代码如下:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Plus {
public:
ListNode* plusAB(ListNode* a, ListNode* b) {
// write code here
if(a==NULL && b==NULL)
return NULL;
if(b==NULL)
return a;
if(a==NULL)
return b;
ListNode* l3=new ListNode(-1);
ListNode* newnode=l3;
int flag=0;
while(a!=NULL || b!=NULL)
{
int n1=a?a->val:0;
int n2=b?b->val:0;
int sum=n1+n2+flag;
if(sum>=10)
{
flag=1;
sum-=10;
}
else{
flag=0;
}
newnode->next=new ListNode(sum);
newnode=newnode->next;
if(a) a=a->next;
if(b) b=b->next;
}
if(flag) newnode->next=new ListNode(1);
return l3->next;
}
};
作者:YunLambert
-------------------------------------------
个性签名:一名会音乐、爱健身的不合格程序员
可以Follow博主的Github哦(っ•̀ω•́)っ✎⁾⁾