LintCode Q167 Add Two Numbers reversed in Python

  • Jinhai ZHOU
  • 6 Minutes
  • 2016年11月12日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists(self, l1, l2):
# write your code here
# step 1: get length of l1 and l2
len_1 = 0
len_2 = 0
current = l1
while current is not None:
len_1 += 1
current = current.next
current = l2
while current is not None:
len_2 += 1
current = current.next
# suppose len_1 < len_2
if len_1 > len_2:
l1, l2 = l2, l1
gap = len_1 - len_2
else:
gap = len_2 - len_1
while gap > 0:
dummy = ListNode(0)
dummy.next = l1
l1 = dummy
gap -= 1
# now l1 and l2 are same length
return self.addList(l1, l2)[0]
def addList(self, l1, l2):
# return node and carry
next_node, carry = None, 0
if l1.next is not None:
[next_node, carry] = self.addList(l1.next, l2.next)
sum_val = l1.val + l2.val + carry
this_val = sum_val%10
carry = sum_val/10
current_node = ListNode(val)
current_node.next = next_node
return [current_node, carry]
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。