Skip to content

Commit 46f2a8a

Browse files
committed
🐜 Study: Add Two Numbers
1 parent 1581fa4 commit 46f2a8a

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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* l1, ListNode* l2) {
14+
ListNode *head = NULL, *tail = NULL;
15+
int add = 0;
16+
while (l1 != NULL or l2 != NULL or add > 0) {
17+
ListNode *node = new ListNode(0, NULL);
18+
int val = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + add;
19+
node->val = val % 10;
20+
add = val / 10;
21+
if (l1) l1 = l1->next;
22+
if (l2) l2 = l2->next;
23+
if (!head) head = node;
24+
else tail->next = node;
25+
tail = node;
26+
}
27+
return head;
28+
}
29+
};

0 commit comments

Comments
Β (0)