-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path002_add_two_numbers.cpp
89 lines (86 loc) · 2.33 KB
/
002_add_two_numbers.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution
{
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode * result = new ListNode(0);
ListNode *cur = result;
int carry=0;
while(l1 != nullptr or l2 != nullptr or carry != 0)
{
int v1,v2;
v1=v2=0;
if(l1 != nullptr)
{
v1=l1->val;
l1=l1->next;
}
if(l2 != nullptr)
{
v2=l2->val;
l2=l2->next;
}
int temp = v1+v2+carry;
int value = temp % 10;
cur->val = value;
carry = temp / 10;
if(l1 != nullptr or l2 != nullptr or carry != 0)
{
cur->next =new ListNode(0);
cur=cur->next;
}
}
return result;
}
ListNode* addTwoNumbers2(ListNode* l1, ListNode* l2)
{
ListNode * header = new ListNode(0);
ListNode *cur = header;
int carry=0;
while(l1 != nullptr or l2 != nullptr or carry != 0)
{
int v1,v2;
v1=v2=0;
if(l1 != nullptr)
{
v1=l1->val;
l1=l1->next;
}
if(l2 != nullptr)
{
v2=l2->val;
l2=l2->next;
}
int temp = v1+v2+carry;
int value = temp % 10;
carry = temp / 10;
cur->next =new ListNode(value);
cur=cur->next;
}
return header->next;
}
};
int main(int argc, char const *argv[])
{
ListNode a(5),b(4),c(3),h(8);
ListNode d(5),e(6),f(4);
// a.next = &b;
// b.next=&c;
// c.next=&h;
// d.next=&e;
// e.next=&f;
Solution s;
ListNode* res = s.addTwoNumbers2(&a,&d);
cout<<res->val<<res->next->val;
//cout<<res->val<<res->next->val<<res->next->next->val;
//<<res->next->next->next->val<<endl;
return 0;
}