Skip to content

Commit e0f5ff9

Browse files
committed
Time: 46 ms (49.29%), Space: 71.5 MB (53.69%) - LeetHub
1 parent f9e6eed commit e0f5ff9

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
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* l1, ListNode* l2) {
14+
ListNode* dummy=new ListNode();
15+
ListNode* temp=dummy;
16+
int carry=0;
17+
while(l1!=NULL || l2!=NULL || carry){
18+
int sum=0;
19+
if(l1!=NULL){
20+
sum+=l1->val;
21+
l1=l1->next;
22+
}
23+
if(l2!=NULL){
24+
sum+=l2->val;
25+
l2=l2->next;
26+
}
27+
sum+=carry;
28+
carry=sum/10;
29+
ListNode* newnode=new ListNode(sum%10);
30+
temp->next=newnode;
31+
temp=temp->next;
32+
}
33+
return dummy->next;
34+
}
35+
};

0 commit comments

Comments
 (0)