第一想法是顺着题目的原因,将两链表分别转化为一个数字,再将数字相加,然后把结果转化为字符串,存到答案链表中。但是数据太大会溢出!
所以,要在计算一对数字的过程当中直接存储一个结果,注意结果大于9时进位,删去最终链表的最后一个节点。
/**
* 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) {
int carry=;
int x,y,z;
ListNode* head = new ListNode(-);
ListNode* use = new ListNode(-);
ListNode* t = new ListNode(-);
head->next = t;
while(l1 || l2)
{
if(!l1)
{
x = ;
}else x = l1->val; if(!l2)
{
y = ;
}else y = l2->val; z = x + y + carry;
carry = ;
if(z>)
{
carry = ;
z = z-;
}
t->val = z;
t->next = new ListNode(-);
use = t;
t = t->next;
t->next = NULL; if(l1)
{
l1 = l1->next;
}
if(l2)
{
l2 = l2->next;
}
}
if(carry)
{
t->val = carry;
t->next = new ListNode(-);
use = t;
t = t->next;
t->next = NULL;
}
t = head->next;
use->next = NULL;
return t;
}
};