File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-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(int x) : val(x), next(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ ListNode *addTwoNumbers (ListNode *l1, ListNode *l2) {
12
+ // Start typing your C/C++ solution below
13
+ // DO NOT write int main() function
14
+ ListNode *h=l1,*p1,*p2;
15
+ int carry=0 ;
16
+ while (l1&&l2)
17
+ {
18
+ l1->val =l1->val +l2->val +carry;
19
+ carry=l1->val >9 ;
20
+ l1->val %=10 ;
21
+ p1=l1;p2=l2;
22
+ l1=l1->next ;
23
+ l2=l2->next ;
24
+ }
25
+ if (!l1&&!l2&&carry)
26
+ {
27
+ p1->next =new ListNode (1 );
28
+ }
29
+ if (l1)
30
+ {
31
+ while (l1)
32
+ {
33
+ l1->val =l1->val +carry;
34
+ carry=l1->val >9 ;
35
+ l1->val %=10 ;
36
+ p1=l1;
37
+ l1=l1->next ;
38
+ }
39
+ if (carry)
40
+ {
41
+ p1->next =new ListNode (1 );
42
+ }
43
+ }
44
+ else if (l2)
45
+ {
46
+ p1->next =l2;
47
+ while (l2)
48
+ {
49
+ l2->val =l2->val +carry;
50
+ carry=l2->val >9 ;
51
+ l2->val %=10 ;
52
+ p2=l2;
53
+ l2=l2->next ;
54
+ }
55
+ if (carry)
56
+ {
57
+ p2->next =new ListNode (1 );
58
+ }
59
+ }
60
+ return h;
61
+ }
62
+ };
You can’t perform that action at this time.
0 commit comments