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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
个人理解:根据题目意思,数字是以相反的顺序储存的,因此,要计算的是342+465=807,也就是简单的加法,其中要注意的两个数字相加产生的进位问题,用“/”来求得进位,剩余的便是链表的依次相加了,同时还要记得判断链表长度不等的情况。
/**
* 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* sumlist=new ListNode(-1);
ListNode* res=sumlist;
int temp=0;
while(l1!=NULL || l2!=NULL|| temp!=0)
{
int l1val=l1==NULL ? 0:l1->val;
int l2val=l2==NULL ? 0:l2->val;
int sum=l1val+l2val+temp;
temp=sum/10;
sum%=10;
res->next=new ListNode(sum);
res=res->next;
l1=l1==NULL ? NULL:l1->next;
l2=l2==NULL?NULL:l2->next;
}
ListNode *ans=sumlist->next;
delete sumlist;
return ans;
}
};