-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathadd-two-numbers.cpp
35 lines (31 loc) · 939 Bytes
/
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
/**
* 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* p, ListNode* q) {
ListNode* head = new ListNode(0);
ListNode* dummy = head;
int c = 0;
int d = 0;
while(p != NULL or q != NULL){
int sum = (p != NULL ? p->val : 0) + (q != NULL ? q->val : 0) + c;
d = sum % 10;
c = sum / 10;
head->next = new ListNode(d);
p = (p != NULL ? p->next : NULL);
q = (q != NULL ? q->next: NULL);
head = head->next;
}
if(c)
head->next = new ListNode(1);
return dummy->next;
}
};