forked from ccgcv/Cplus-plus-for-hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd2numbers.cpp
44 lines (41 loc) · 1.01 KB
/
add2numbers.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
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode * head = NULL;
ListNode * tail = NULL;
int carry = 0;
while(l1 != NULL || l2 != NULL || carry)
{
int a = 0;
if(l1 != NULL)
{
a = l1->val;
}
int b = 0;
if(l2 != NULL)
{
b = l2->val;
}
int sum = a + b + carry;
int num = sum % 10;
ListNode * temp = new ListNode(num);
if(head == NULL)
{
head = temp;
tail = temp;
}
else
{
tail->next = temp;
tail= tail->next;
}
carry = sum/10;
if(l1 != NULL)
{
l1 = l1->next;
}
if(l2 != NULL)
{
l2 = l2->next;
}
}
return head;
}