1
+ //
2
+ // Created by DHL on 2022年4月27日.
3
+ //
4
+
5
+ /* *
6
+ * Definition for singly-linked list.
7
+ * struct ListNode {
8
+ * int val;
9
+ * ListNode *next;
10
+ * ListNode() : val(0), next(nullptr) {}
11
+ * ListNode(int x) : val(x), next(nullptr) {}
12
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
13
+ * };
14
+ */
15
+ class Solution {
16
+ public:
17
+ ListNode *reverse (ListNode *head) {
18
+ ListNode *pre = nullptr ;
19
+ while (head) {
20
+ ListNode *next = head->next ;
21
+ head->next = pre ;
22
+ pre = head;
23
+ head = next;
24
+ }
25
+ return pre ;
26
+ }
27
+
28
+ ListNode *addTwoNumbers (ListNode *l1, ListNode *l2) {
29
+ ListNode *p1 = reverse (l1);
30
+ ListNode *p2 = reverse (l2);
31
+ int carry = 0 ;
32
+ ListNode *head = nullptr ;
33
+ while ((p1 || p2)) {
34
+ int a = p1 ? p1->val : 0 ;
35
+ int b = p2 ? p2->val : 0 ;
36
+ int sum = a + b + carry;
37
+ carry = sum / 10 ;
38
+ ListNode *node = new ListNode (sum % 10 );
39
+ node->next = head;
40
+ head = node;
41
+ p1 = p1 ? p1->next : nullptr ;
42
+ p2 = p2 ? p2->next : nullptr ;
43
+ }
44
+ if (carry > 0 ) {
45
+ ListNode *node = new ListNode (carry);
46
+ node->next = head;
47
+ head = node;
48
+ }
49
+ return head;
50
+ }
51
+
52
+ };
0 commit comments