File tree 1 file changed +21
-19
lines changed
1 file changed +21
-19
lines changed Original file line number Diff line number Diff line change 3
3
* Add the two numbersand return the sum as a linked list.
4
4
*/
5
5
6
- /*
6
+ #include < memory>
7
+
8
+ /*
7
9
* Definition for singly-linked list.
8
10
*/
9
11
struct ListNode {
10
12
int val;
11
13
ListNode *next;
12
- ListNode () : val(0 ), next(nullptr ) {}
14
+ explicit ListNode () : val(0 ), next(nullptr ) {}
13
15
ListNode (int x) : val(x), next(nullptr ) {}
14
16
ListNode (int x, ListNode *next) : val(x), next(next) {}
15
17
};
16
18
17
19
class Solution {
18
20
public:
19
- ListNode* addTwoNumbers (ListNode* l1, ListNode* l2) {
20
- int carry = 0 ;
21
- ListNode head;
22
- ListNode* sum = &head;
23
-
24
- while (l1 || l2) {
25
- int val = carry + (l1 ? l1->val : 0 ) + (l2 ? l2->val : 0 );
26
- carry = val / 10 ;
27
- sum->next = new ListNode (val % 10 );
28
- sum = sum->next ;
29
- l1 = (l1 ? l1->next : nullptr );
30
- l2 = (l2 ? l2->next : nullptr );
31
- }
32
- if (carry) {
33
- sum->next = new ListNode (carry);
34
- }
21
+ ListNode* addTwoNumbers (ListNode* l1, ListNode* l2) {
22
+ int carry = 0 ;
23
+ std::unique_ptr<ListNode> head (new ListNode (0 ));
24
+ ListNode* sum = head.get ();
35
25
36
- return head.next ;
26
+ while (l1 || l2) {
27
+ int val = carry + (l1 ? l1->val : 0 ) + (l2 ? l2->val : 0 );
28
+ carry = val/10 ;
29
+ sum->next = new ListNode (val%10 );
30
+ sum = sum->next ;
31
+ l1 = (l1 ? l1->next : nullptr );
32
+ l2 = (l2 ? l2->next : nullptr );
37
33
}
34
+ if (carry){
35
+ sum->next = new ListNode (carry);
36
+ }
37
+
38
+ return head->next ;
39
+ }
38
40
};
You can’t perform that action at this time.
0 commit comments