最后一发!
应该算法有问题,不能用加法来操作,这样会导致溢出,不过改了一下,发现没有必要用队列,一切很有序很自然,上修改后的代码:
class Solution
{
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
long a=listtolong(l1);
long b=listtolong(l2);
long sum=a+b;
return longtolist(sum);
}
long listtolong(ListNode* t1)
{
unsigned long sum = 0;
unsigned long temp = 1;
while (t1!=NULL)
{
sum = sum + t1->val*temp;
temp = temp * 10;
t1 = t1->next;
}
return sum;
}
ListNode* longtolist(unsigned long t)
{
ListNode* t2 = new ListNode(0);
ListNode* t1 = t2;
while (t != 0)
{
t2->val = t % 10;
if (t/10!=0)
{
ListNode* t3 = new ListNode(0);
t2->next = t3;
t2 = t3;
}
t = t / 10;
}
return t1;
}
};