-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddTwo.cpp
More file actions
70 lines (59 loc) · 1.34 KB
/
addTwo.cpp
File metadata and controls
70 lines (59 loc) · 1.34 KB
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
//
// Created by uladzislau on 4.7.17.
//
#include <iostream>
using namespace std;
class List{
public:
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int count(ListNode* l){
int length = 1;
while(l->next != NULL)
{
length++;
l=l->next;
}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
int carry = 0, buf, value, num1, num2;
ListNode *first = NULL, *prev = NULL;
while(l1 || l2){
if(l1)
num1 = l1->val;
else
num1 = 0;
if(l2)
num2 = l2->val;
else
num2 = 0;
buf = num1 + num2 + carry;
carry = buf/10;
value = buf % 10;
ListNode* cur = new ListNode(value);
if(!first)
first = cur;
if(prev)
prev->next = cur;
prev = cur;
if(l1)
l1 = l1->next;
else
l1 = NULL;
if(l2)
l2 = l2->next;
else
l2 = NULL;
}
if(carry > 0)
{
ListNode *l = new ListNode(carry);
prev->next = l;
}
return first;
}
};