-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_Two_Numbers.cpp
More file actions
33 lines (32 loc) · 903 Bytes
/
Add_Two_Numbers.cpp
File metadata and controls
33 lines (32 loc) · 903 Bytes
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
# number : 2
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p = l1, *q = l2;
ListNode *dummy = new ListNode(0);
ListNode *curr = dummy;
int flag = 0;
while (p != nullptr || q != nullptr) {
int a = (p != nullptr) ? p->val : 0;
int b = (q != nullptr) ? q->val : 0;
int tmp = a + b + flag;
curr->next = new ListNode(tmp % 10);
flag = (tmp >= 10) ? 1 : 0;
curr = curr->next;
if (p != nullptr) p = p->next;
if (q != nullptr) q = q->next;
}
if (flag == 1) {
curr->next = new ListNode(1);
}
return dummy->next;
}
};