File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Recursion/0002-add-two-numbers Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments