Skip to content

Commit 778d229

Browse files
authored
Add files via upload
1 parent e2060ca commit 778d229

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

002_AddTwoNums.cpp

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#include <iostream>
2+
#include <list>
3+
#include <map>
4+
#include <string>
5+
#include <algorithm>
6+
7+
using namespace std;
8+
9+
10+
// Definition for singly-linked list.
11+
struct ListNode {
12+
int val;
13+
ListNode *next;
14+
ListNode() : val(0), next(nullptr) {}
15+
ListNode(int x) : val(x), next(nullptr) {}
16+
ListNode(int x, ListNode *next) : val(x), next(next) {}
17+
};
18+
19+
class Solution{
20+
21+
public:
22+
23+
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
24+
//ListNode *list_res = new ListNode;
25+
//list_res -> next = nullptr;
26+
27+
int carry = 0;
28+
ListNode head = ListNode(0);
29+
ListNode *temp = &head;
30+
while (l1 || l2 || carry)
31+
{
32+
if (l1)
33+
{
34+
carry = carry + l1->val;
35+
l1 = l1 ->next;
36+
}
37+
if (l2)
38+
{
39+
carry = carry + l2->val;
40+
l2 = l2 ->next;
41+
}
42+
temp -> next = new ListNode(carry % 10);
43+
temp = temp -> next;
44+
carry = carry / 10;
45+
46+
}
47+
return head.next;
48+
}
49+
};
50+
51+
void ListNode_output(ListNode * list_input)
52+
{
53+
while(list_input){
54+
cout << list_input->val << ' ';
55+
list_input = list_input->next;
56+
}
57+
cout << endl;
58+
}
59+
60+
int main()
61+
{
62+
/*l1*/
63+
ListNode *l1_1 = new ListNode;
64+
l1_1 -> val = 2;
65+
l1_1 -> next = nullptr;
66+
67+
ListNode *l1_2 = new ListNode;
68+
l1_2 -> val = 4;
69+
l1_2 -> next = nullptr;
70+
71+
ListNode *l1_3 = new ListNode;
72+
l1_3 -> val = 3;
73+
l1_3 -> next = nullptr;
74+
75+
l1_1 -> next = l1_2;
76+
l1_2 -> next = l1_3;
77+
78+
/*l2*/
79+
ListNode *l2_1 = new ListNode;
80+
l2_1 -> val = 5;
81+
l2_1 -> next = nullptr;
82+
83+
ListNode *l2_2 = new ListNode;
84+
l2_2 -> val = 6;
85+
l2_2 -> next = nullptr;
86+
87+
ListNode *l2_3 = new ListNode;
88+
l2_3 -> val = 4;
89+
l2_3 -> next = nullptr;
90+
91+
l2_1 -> next = l2_2;
92+
l2_2 -> next = l2_3;
93+
94+
Solution Sol1;
95+
ListNode_output(Sol1.addTwoNumbers(l1_1, l2_1));
96+
97+
98+
return 0;
99+
}

0 commit comments

Comments
 (0)