File tree 1 file changed +40
-0
lines changed
1 file changed +40
-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* head = l1;
15
+ ListNode* ans = head;
16
+ int sum, a = 0 , b = 0 , remainder = 0 ;
17
+ while (l1 || l2 || remainder ) {
18
+ a = 0 , b = 0 ;
19
+ if (l1){
20
+ a = l1->val ;
21
+ l1 = l1->next ;
22
+ }
23
+ if (l2){
24
+ b = l2->val ;
25
+ l2 = l2->next ;
26
+ }
27
+ sum = a + b + remainder ;
28
+ head->next = new ListNode (sum%10 );
29
+ remainder = sum/10 ;
30
+ head = head->next ;
31
+ }
32
+ ListNode* temp = ans;
33
+ ans = ans->next ;
34
+ delete temp;
35
+ return ans;
36
+ }
37
+ };
38
+
39
+ // Runtime: 36 ms, faster than 40.34% of C++ online submissions for Add Two Numbers.
40
+ // Memory Usage: 71.5 MB, less than 11.15% of C++ online submissions for Add Two Numbers.
You can’t perform that action at this time.
0 commit comments