File tree 1 file changed +35
-0
lines changed
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* p, ListNode* q) {
14
+ ListNode* head = new ListNode (0 );
15
+ ListNode* dummy = head;
16
+
17
+ int c = 0 ;
18
+ int d = 0 ;
19
+ while (p != NULL or q != NULL ){
20
+ int sum = (p != NULL ? p->val : 0 ) + (q != NULL ? q->val : 0 ) + c;
21
+ d = sum % 10 ;
22
+ c = sum / 10 ;
23
+
24
+ head->next = new ListNode (d);
25
+ p = (p != NULL ? p->next : NULL );
26
+ q = (q != NULL ? q->next : NULL );
27
+ head = head->next ;
28
+ }
29
+
30
+ if (c)
31
+ head->next = new ListNode (1 );
32
+
33
+ return dummy->next ;
34
+ }
35
+ };
You can’t perform that action at this time.
0 commit comments