File tree Expand file tree Collapse file tree 1 file changed +80
-4
lines changed
Expand file tree Collapse file tree 1 file changed +80
-4
lines changed Original file line number Diff line number Diff line change @@ -48,11 +48,11 @@ https://leetcode-cn.com/problems/add-two-numbers/
4848
4949## 代码
5050
51- - 语言支持:JS,C++
51+ - 语言支持:JS,C++,Java,Python
5252
53- JavaScript:
53+ JavaScript Code :
5454
55- ``` js
55+ ``` js
5656/**
5757 * Definition for singly-linked list.
5858 * function ListNode(val) {
@@ -102,7 +102,7 @@ var addTwoNumbers = function (l1, l2) {
102102};
103103```
104104
105- C++
105+ C++ Code:
106106
107107> C++代码与上面的 JavaScript 代码略有不同:将 carry 是否为 0 的判断放到了 while 循环中
108108
@@ -141,6 +141,82 @@ public:
141141};
142142```
143143
144+
145+ Java Code:
146+
147+ ```java
148+ class Solution {
149+ public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
150+ ListNode dummyHead = new ListNode(0);
151+ ListNode cur = dummyHead;
152+ int carry = 0;
153+
154+ while(l1 != null || l2 != null)
155+ {
156+ int sum = carry;
157+ if(l1 != null)
158+ {
159+ sum += l1.val;
160+ l1 = l1.next;
161+ }
162+ if(l2 != null)
163+ {
164+ sum += l2.val;
165+ l2 = l2.next;
166+ }
167+ // 创建新节点
168+ carry = sum / 10;
169+ cur.next = new ListNode(sum % 10);
170+ cur = cur.next;
171+
172+ }
173+ if (carry > 0) {
174+ cur.next = new ListNode(carry);
175+ }
176+ return dummyHead.next;
177+ }
178+ }
179+
180+ ```
181+
182+
183+ Python Code:
184+
185+ ``` py
186+ class Solution :
187+ def addTwoNumbers (self , l1 , l2 ):
188+ """
189+ :type l1: ListNode
190+ :type l2: ListNode
191+ :rtype: ListNode
192+ """
193+ res= ListNode(0 )
194+ head= res
195+ carry= 0
196+ while l1 or l2 or carry!= 0 :
197+ sum = carry
198+ if l1:
199+ sum += l1.val
200+ l1= l1.next
201+ if l2:
202+ sum += l2.val
203+ l2= l2.next
204+ # set value
205+ if sum <= 9 :
206+ res.val= sum
207+ carry= 0
208+ else :
209+ res.val= sum % 10
210+ carry= sum // 10
211+ # creat new node
212+ if l1 or l2 or carry!= 0 :
213+ res.next= ListNode(0 )
214+ res= res.next
215+ return head
216+
217+ ```
218+
219+
144220** 复杂度分析**
145221
146222- 时间复杂度:$O(N)$
You can’t perform that action at this time.
0 commit comments