-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd_Two_Numbers.cc
52 lines (50 loc) · 1.27 KB
/
Add_Two_Numbers.cc
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
typedef struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
} ListNode;
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *head = NULL;
ListNode *p = NULL;
ListNode *q = NULL;
int carry = 0;
ListNode* i1 = l1;
ListNode* i2 = l2;
while(i1 || i2)
{
int sum = carry;
if (i1)
{
sum += i1->val;
i1 = i1->next;
}
if (i2)
{
sum += i2->val;
i2 = i2->next;
}
int cur_digit = sum % 10;
p = new ListNode(cur_digit);
if (head == NULL)
{
head = p;
q = head;
}
else
{
q->next = p;
q = p;
}
p = p->next;
carry = sum / 10;
}
if (carry)
{
p = new ListNode(carry);
q->next = p;
}
return head;
}
};