Add Two Numbers

1557 / 1558 test cases passed.只有一个样例没有通过,应该是越界的问题,暂时不管了,这道题一开始按照自己的思路来,然后就浪费了一上午的时间,后面觉得还是得参考别人的思路,看了别人的解答后,发现自己智商还是挺lower的,只会用最简单的方法来做,而没有一丝创造性;现在贴出代码,算法的思路主要是利用了两个函数,一个是链表转为long 整形,另一个是long 整形转为链表。其中用队列来操作好像挺符合的,代码如下:

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)
{
queue<unsigned long long>b;
long sum = 0;
long temp = 1;
while (t1!=NULL)
{
b.push(t1->val);
t1 = t1->next;
}
while (b.size()!=0)
{
sum = sum + b.front()*temp;
temp = temp * 10;
b.pop();
}
return sum;
}


ListNode* longtolist(long t)
{
queue<unsigned long long>c;
while (t!=0)
{
c.push(t%10);
t = t / 10;
}
ListNode* t2 = new ListNode(0);
ListNode* t1 = t2;
while (c.size()!=0)
{
t2->val = c.front();
c.pop();
if (c.size() != 0)
{
ListNode* t3 = new ListNode(0);
t2->next = t3;
t2 = t3;
}
}
return t1;
}
};

posted @ 2016-08-05 13:17  追风筝的恐龙  阅读(88)  评论(0编辑  收藏  举报