@@ -37,7 +37,7 @@ Output: 7 -> 8 -> 0 -> 7
3737
3838## 代码
3939
40- - 语言支持:JS,C++
40+ - 语言支持:JS,C++, Python3
4141
4242JavaScript Code:
4343
@@ -210,3 +210,50 @@ private:
210210 }
211211};
212212```
213+
214+ Python Code:
215+
216+ ``` python
217+ # Definition for singly-linked list.
218+ # class ListNode:
219+ # def __init__(self, x):
220+ # self.val = x
221+ # self.next = None
222+
223+ class Solution :
224+ def addTwoNumbers (self , l1 : ListNode, l2 : ListNode) -> ListNode:
225+ def listToStack (l : ListNode) -> list :
226+ stack, c = [], l
227+ while c:
228+ stack.append(c.val)
229+ c = c.next
230+ return stack
231+
232+ # transfer l1 and l2 into stacks
233+ stack1, stack2 = listToStack(l1), listToStack(l2)
234+
235+ # add stack1 and stack2
236+ diff = abs (len (stack1) - len (stack2))
237+ stack1 = ([0 ]* diff + stack1 if len (stack1) < len (stack2) else stack1)
238+ stack2 = ([0 ]* diff + stack2 if len (stack2) < len (stack1) else stack2)
239+ stack3 = [x + y for x, y in zip (stack1, stack2)]
240+
241+ # calculate carry for each item in stack3 and add one to the item before it
242+ carry = 0
243+ for i, val in enumerate (stack3[::- 1 ]):
244+ index = len (stack3) - i - 1
245+ carry, stack3[index] = divmod (val + carry, 10 )
246+ if carry and index == 0 :
247+ stack3 = [1 ] + stack3
248+ elif carry:
249+ stack3[index - 1 ] += 1
250+
251+ # transfer stack3 to a linkedList
252+ result = ListNode(0 )
253+ c = result
254+ for item in stack3:
255+ c.next = ListNode(item)
256+ c = c.next
257+
258+ return result.next
259+ ```
0 commit comments