您的位置:首页 > 其它

leetcode 2 Add Two Numbers

2015-09-11 11:04 281 查看
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

/**

* Definition for singly-linked list.

* struct ListNode {

* int val;

* ListNode *next;

* ListNode(int x) : val(x), next(NULL) {}

* };

*/
#include <vector>
#include <cstdlib>
#include <cstdio>
using namespace std;

struct ListNode {

int val;

ListNode *next;

ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* head = NULL;
ListNode* tail = NULL;
ListNode* p = l1;
ListNode* q = l2;
int carry = 0;
while(p != NULL && q != NULL)
{
ListNode* new_v = (ListNode*)malloc(sizeof(ListNode));
new_v->next = NULL;
if(p->val + q->val + carry >= 10)
{
new_v->val = p->val + q->val + carry -10;
carry = 1;
}
else
{
new_v->val = p->val + q->val + carry;
carry = 0;
}
if(head == NULL)
{
head = new_v;
tail = new_v;
}
else
{
tail->next = new_v;
tail = new_v;
}
p = p->next;
q = q->next;
}
while(p != NULL)
{
ListNode* new_v = (ListNode*)malloc(sizeof(ListNode));
new_v->next = NULL;
if(p->val + carry >= 10)
{
new_v->val = p->val + carry -10;
carry = 1;
}
else
{
new_v->val = p->val + carry;
carry = 0;
}
if(head == NULL)
{
head = new_v;
tail = new_v;
}
else
{
tail->next = new_v;
tail = new_v;
}
p = p->next;
}
while(q != NULL)
{
ListNode* new_v = (ListNode*)malloc(sizeof(ListNode));
new_v->next = NULL;
if(q->val + carry >= 10)
{
new_v->val = q->val + carry -10;
carry = 1;
}
else
{
new_v->val = q->val + carry;
carry = 0;
}
if(head == NULL)
{
head = new_v;
tail = new_v;
}
else
{
tail->next = new_v;
tail = new_v;
}
q = q->next;
}
if(carry == 1)
{
ListNode* new_v = (ListNode*)malloc(sizeof(ListNode));
new_v->next = NULL;
new_v->val = 1;
if(head == NULL)
{
head = new_v;
tail = new_v;
}
else
{
tail->next = new_v;
tail = new_v;
}

}
return head;

}

};

int main()
{
ListNode* l1 = NULL, *l2 = NULL;
ListNode* t1 = NULL, *t2 = NULL;
int a, b;
scanf("%d", &a);
for(int i = 1; i <= a; i++)
{
int x;
scanf("%d", &x);
ListNode* new_p = (ListNode*)malloc(sizeof(ListNode));
new_p->next = NULL;
new_p->val = x;

if(l1 == NULL)
{
l1 = new_p;
t1 = new_p;
}
else
{
t1->next = new_p;
}
}
scanf("
4000
%d", &a);
for(int i = 1; i <= a; i++)
{
int x;
scanf("%d", &x);
ListNode* new_p = (ListNode*)malloc(sizeof(ListNode));
new_p->next = NULL;
new_p->val = x;

if(l2 == NULL)
{
l2 = new_p;
t2 = new_p;
}
else
{
t2->next = new_p;
}
}

Solution s;
ListNode* r = s.addTwoNumbers(l1, l2);

while(r != NULL)
{
printf("%d ", r->val);
r = r->next;
}
return 0;

}

读题一定要仔细。

还有题目没有说两个输入链表长度相等,就要考虑不相等的情况。

还有最后一位需要进位。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: