题目描述:
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
/**
* 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* p=l1;
ListNode* q=l2;
ListNode* r=new ListNode(0);
ListNode* result=r;
bool carry=false;
while(1)
{
ListNode* node=new ListNode(0);
if(carry==true)
{
carry=false;
node->val=1;
}
if(p!=NULL&&q!=NULL)
{
node->val+=p->val+q->val;
if(node->val>9)
{
node->val=node->val%10;
carry=true;
}
r->next=node;
r=node;
p=p->next;
q=q->next;
}
else if(p!=NULL&&q==NULL)
{
node->val+=p->val;
if(node->val>9)
{
node->val=node->val%10;
carry=true;
}
r->next=node;
r=node;
p=p->next;
}
else if(p==NULL&&q!=NULL)
{
node->val+=q->val;
if(node->val>9)
{
node->val=node->val%10;
carry=true;
}
r->next=node;
r=node;
q=q->next;
}
else if(p==NULL&&q==NULL)
{
if(node->val==1)
{
r->next=node;
r=node;
}
break;
}
}
return result->next;
}
};
递归解法,将加法分解为当前位数相加,并把后面位数的相加结果作为当前位数的next,需要注意的是递归需要将进位传参,参加后续计算。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
return recurAdd(l1,l2,0);
}
ListNode* recurAdd(ListNode* l1, ListNode* l2,int carry)
{
ListNode* node=new ListNode(0);
if(l1==NULL&&l2==NULL)
{
if(carry==1)
{
node->val=1;
return node;
}
else return NULL;
}
else if(l1==NULL&&l2!=NULL)
{
node->val=l2->val+carry;
if(node->val>9)
{
node->val%=10;
carry=1;
}
else carry=0;
node->next=recurAdd(NULL,l2->next,carry);
}
else if(l1!=NULL&&l2==NULL)
{
node->val=l1->val+carry;
if(node->val>9)
{
node->val%=10;
carry=1;
}
else carry=0;
node->next=recurAdd(l1->next,NULL,carry);
}
else if(l1!=NULL&&l2!=NULL)
{
node->val=l1->val+l2->val+carry;
if(node->val>9)
{
node->val%=10;
carry=1;
}
else carry=0;
node->next=recurAdd(l1->next,l2->next,carry);
}
return node;
}
};