题目描述:
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 contain a single digit. Add the two numbers and return it as a linked list.You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
思路:就是两个数的加法,唯一要注意的是最高位之后还有进位要将其加上。
#include<cstdio>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
//结果链表的头节点
ListNode* result = NULL;
//结果链表的游标
ListNode* pointer = NULL;
int num1 = 0;
int num2 = 0;
//进位数
int addition = 0;
while(l1!=NULL||l2!=NULL)
{
num1 = (l1==NULL)?(0):(l1->val);
num2 = (l2==NULL)?(0):(l2->val);
//该位节点的数值
int val = (num1+num2+addition)%10;
//更新下一位的进位数
addition = (num1+num2+addition)/10;
if(result==NULL)
{
result = new ListNode(val);
pointer = result;
}
else
{
ListNode* node = new ListNode(val);
pointer->next = node;
pointer = node;
}
if(l1!=NULL)
l1 = l1->next;
if(l2!=NULL)
l2 = l2->next;
}
//如果最高位计算完之后还有进位,要将其加上
if(addition!=0)
{
ListNode* node = new ListNode(addition);
pointer->next = node;
}
return result;
}
int main(){
ListNode* node1 = new ListNode(5);
ListNode* node2 = new ListNode(4);
ListNode* node3 = new ListNode(3);
node1->next = node2;
node2->next = node3;
ListNode* node4 = new ListNode(5);
ListNode* node5 = new ListNode(6);
ListNode* node6 = new ListNode(4);
ListNode* node7 = new ListNode(4);
node4->next = node5;
node5->next = node6;
node6->next = node7;
ListNode* result = addTwoNumbers(node1,node4);
while(result!=NULL)
{
printf("%d",result->val);
if(result->next!=NULL)
printf("->");
result = result->next;
}
return 0;
}