您的位置:首页 > 其它

leetcode

2015-08-25 11:35 309 查看
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;

unsigned long int v1 = -1, v2 = -1, v3 = 0;

ListNode *p1 = l1, *p2 = l2, *l3 = NULL, *p3 = l3;
ListNode *pt = NULL;
int count = 0;
while (p1){
if ( count==0 )
v1 = p1->val;
else{
int temp=1;
for (int i = 1; i <= count; i++)
temp = 10 * temp;

v1 = temp* (p1->val) + v1;
}

count++;
p1 = p1->next;
}

count = 0;
while (p2){
if (count == 0)
v2 = p2->val;
else{
int temp = 1;
for (int i = 1; i <= count; i++)
temp = 10 * temp;

v2 = temp* (p2->val) + v2;
}

count++;
p2 = p2->next;
}

v3 = v1 + v2;

while (v3 / 10 != 0){
pt = new ListNode(v3 % 10);
if (l3 == NULL){
pt->next = NULL;
l3 = pt;
}
else{
pt->next = p3->next;
p3->next = pt;
p3 = pt;
}
v3 = v3 / 10;
p3 = pt;
}
if (v3 != 0){
pt = new ListNode(v3);
pt->next = p3->next;
p3->next = pt;
p3 = pt;
}

p3->next = NULL;

return l3;
}
};


You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


在 VS 下能通过各种测试用例,但leetcode上就是不行 ~~ 留着查原因
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: