-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2_Add_Two_Numbers.cpp
46 lines (43 loc) · 1.08 KB
/
2_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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
ListNode *p = l1, *temp;
while(p != NULL && l2 !=NULL)
{
int x = p->val + l2->val + carry;
p->val = x %10;
carry = x/10;
temp = p;
p = p->next;
l2 = l2->next;
}
if( p || l2)
{
if(l2)
temp ->next = l2;
p = temp->next;
while(p)
{
int x = p->val +carry;
p->val = x %10 ;
carry = (x) / 10;
temp = p;
p=p->next;
}
}
if( carry )
temp->next = new ListNode(carry);
return l1;
}
};