题目描述
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
计算两个用链表表示的整数,C++解法
样例
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode *result = NULL,*p,*q,*r = NULL;
int carry = 0,sum = 0,val = 0;
while(l1!=NULL && l2!=NULL)
{
sum = carry+l1->val+l2->val;
//carry保存每次的进位
carry = sum/10;
//val保存每次的剩余数值
val = sum%10;
p = new(ListNode);
p->val = val;
p->next = NULL;
if(!result)
{
result = p;
}else
{
r->next = p;
}
r = p;
l1 = l1->next;
l2 = l2->next;
}
while(l1!=NULL || carry > 0)
{
sum = l1 ? carry + l1->val : carry;
carry = sum / 10;
val = sum % 10;
p = new(ListNode);
p->val = val;
p->next = NULL;
r->next = p;
r = p;
if (!l1)
{
break;
}
l1 = l1->next;
}
while(l2!=NULL || carry > 0)
{
sum = l2 ? carry + l2->val : carry;
carry = sum/10;
val = sum%10;
p = new(ListNode);
p->val = val;
p->next = NULL;
r->next = p;
if (!l2)
{
break;
}
l2 = l2->next;
}
return result;
}