【题目】
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
【答案】
模拟加法:
ListNode * addTwoNumbers(ListNode*l1,ListNode* l2)
{
//链表
ListNode *L;
L=new ListNode(0);
//尾指针
ListNode *Tail;
Tail=L;
int carry=0;
int sum=0;
int val1=0;
int val2=0;
bool isFirst=true;
while (l1 != NULL || l2 !=NULL)
{
//被加数
if (l1 != NULL)
{
val1=l1->val;
l1=l1->next;
}
//加数
if (l2 != NULL)
{
val2=l2->val;
l2=l2->next;
}
//求和
sum = val1 + val2 + carry;
if (sum > 9)
{
sum-=10;
carry=1;
}
else
carry=0;
if (isFirst)
{
L->val= sum;
isFirst = false;
}
else
{ //产生新节点
ListNode *temp;
temp=new ListNode(sum);
Tail->next=temp;
Tail=Tail->next;
}
val1 = 0;
val2 = 0;
}
if (carry == 1 ) //最后一次结果 > 9
{
//产生新节点
ListNode *temp;
temp=new ListNode(1);
Tail->next=temp;
Tail=Tail->next;
}
return L;
}