File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-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 (0 );
15+ ListNode* ll = dummy;
16+ int carry = 0 ;
17+ int sum = 0 ;
18+ while (l1 and l2){
19+ sum = l1->val + l2->val + carry;
20+ ll->next = new ListNode (sum%10 );
21+ ll = ll->next ;
22+ carry = sum/10 ;
23+ l1 = l1->next ;
24+ l2 = l2->next ;
25+ }
26+ while (l1){
27+ sum = l1->val + carry;
28+ ll->next = new ListNode (sum%10 );
29+ ll = ll->next ;
30+ carry = sum/10 ;
31+ l1 = l1->next ;
32+
33+ }
34+ while (l2){
35+ sum = l2->val + carry;
36+ ll->next = new ListNode (sum%10 );
37+ ll = ll->next ;
38+ carry = sum/10 ;
39+ l2 = l2->next ;
40+ }
41+ if (carry != 0 ){
42+ ll->next = new ListNode (carry);
43+ ll = ll->next ;
44+ }
45+ return dummy->next ;
46+ }
47+ };
You can’t perform that action at this time.
0 commit comments