File tree 1 file changed +64
-2
lines changed
0002-Add-Two-Numbers/Article
1 file changed +64
-2
lines changed Original file line number Diff line number Diff line change 32
32
33
33
### 代码实现
34
34
35
- ```
35
+ #### C++
36
+ ``` c++
36
37
// / 时间复杂度: O(n)
37
38
// / 空间复杂度: O(n)
38
39
/* *
@@ -70,7 +71,68 @@ public:
70
71
};
71
72
72
73
```
73
-
74
+ #### Java
75
+ ``` java
76
+ class Solution {
77
+ public ListNode addTwoNumbers (ListNode l1 , ListNode l2 ) {
78
+ ListNode dummyHead = new ListNode (0 );
79
+ ListNode cur = dummyHead;
80
+ int carry = 0 ;
81
+
82
+ while (l1 != null || l2 != null )
83
+ {
84
+ int sum = carry;
85
+ if (l1 != null )
86
+ {
87
+ sum += l1. val;
88
+ l1 = l1. next;
89
+ }
90
+ if (l2 != null )
91
+ {
92
+ sum += l2. val;
93
+ l2 = l2. next;
94
+ }
95
+ // 创建新节点
96
+ carry = sum / 10 ;
97
+ cur. next = new ListNode (sum % 10 );
98
+ cur = cur. next;
99
+
100
+ }
101
+ if (carry > 0 ) {
102
+ cur. next = new ListNode (carry);
103
+ }
104
+ return dummyHead. next;
105
+ }
106
+ }
107
+ ```
108
+ #### Python
109
+ ``` python
110
+ class Solution (object ):
111
+ def addTwoNumbers (self , l1 , l2 ):
112
+ res= ListNode(0 )
113
+ head= res
114
+ carry= 0
115
+ while l1 or l2 or carry!= 0 :
116
+ sum = carry
117
+ if l1:
118
+ sum += l1.val
119
+ l1= l1.next
120
+ if l2:
121
+ sum += l2.val
122
+ l2= l2.next
123
+ # set value
124
+ if sum <= 9 :
125
+ res.val= sum
126
+ carry= 0
127
+ else :
128
+ res.val= sum % 10
129
+ carry= sum // 10
130
+ # creat new node
131
+ if l1 or l2 or carry!= 0 :
132
+ res.next= ListNode(0 )
133
+ res= res.next
134
+ return head
135
+ ```
74
136
75
137
76
138
![ ] ( ../../Pictures/qrcode.jpg )
You can’t perform that action at this time.
0 commit comments