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
链表的小应用,处理BUG花了些时间,总体不难。
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* p=NULL;
ListNode* pN=NULL;
ListNode* pNode=NULL;
int carry = 0,x1,x2,temp;
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
while(l1!=NULL||l2!=NULL){
if(l1==NULL)
x1 = 0;
else
x1 = l1->val;
if(l2==NULL)
x2 = 0;
else
x2 = l2->val;
pNode = new ListNode(x1+x2+carry);
pNode->val = (x1+x2+carry)%10;
carry = (x1+x2+carry)/10;
if(p==NULL)
p = pN =pNode;
else{
pN->next = pNode;
pN = pNode;
}
if(l1!=NULL)
l1= l1->next;
if(l2!=NULL)
l2= l2->next;
}
if(carry==1)
{
pNode = new ListNode(1);
pN->next = pNode;
}
return p;
}