Skip to content

Commit 02df966

Browse files
committed
Time: 36 ms (36.25%), Space: 71.5 MB (43.30%) - LeetHub
1 parent 75a1186 commit 02df966

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

add-two-numbers/add-two-numbers.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* addTwoNumbers(ListNode* p, ListNode* q) {
14+
ListNode* head = new ListNode(0);
15+
ListNode* dummy = head;
16+
17+
int c = 0;
18+
int d = 0;
19+
while(p != NULL or q != NULL){
20+
int sum = (p != NULL ? p->val : 0) + (q != NULL ? q->val : 0) + c;
21+
d = sum % 10;
22+
c = sum / 10;
23+
24+
head->next = new ListNode(d);
25+
p = (p != NULL ? p->next : NULL);
26+
q = (q != NULL ? q->next: NULL);
27+
head = head->next;
28+
}
29+
30+
if(c)
31+
head->next = new ListNode(1);
32+
33+
return dummy->next;
34+
}
35+
};

0 commit comments

Comments
 (0)