【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】
题目描述
有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表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==nullptr)
return b;
if(b==nullptr)
return a;
ListNode *pa = a;
ListNode *pb = b;
ListNode *newList = new ListNode(0);
ListNode *pNode = newList;
int carry = 0;
while(pa&&pb)
{
int data = pa->val+pb->val+carry;
if(data>=10)
{
carry=1;
data-=10;
}
else
{
carry = 0;
}
ListNode *newNode = new ListNode(data);
pNode->next = newNode;
pNode = pNode->next;
pa = pa->next;
pb = pb->next;
}
while(pa!=nullptr)
{
int data = pa->val+carry;
if(data>=10)
{
carry=1;
data-=10;
}
else
{
carry = 0;
}
ListNode *newNode = new ListNode(data);
pNode->next = newNode;
pNode = pNode->next;
pa = pa->next;
}
while(pb!=nullptr)
{
int data = pb->val+carry;
if(data>=10)
{
carry=1;
data-=10;
}
else
{
carry = 0;
}
ListNode *newNode = new ListNode(data);
pNode->next = newNode;
pNode = pNode->next;
pb = pb->next;
}
if(carry)
{
ListNode *newNode = new ListNode(1);
pNode->next = newNode;
pNode = pNode->next;
}
return newList->next;
}
};