这个写的是贼尴尬,人家十几行写完了,我写n多,继续学习哎!
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def set_next(self, next):
self.next = next
def get_next_value(self):
if self.next:
return self.next.value
class Link(object):
def __init__(self):
self.root: Node = None
self.length = 0
def add(self, node: Node):
if not self.root:
self.root = node
else:
temp = self.root
while temp.next:
temp = temp.next
temp.next = node
self.length += 1
def show(self):
temp = self.root
while temp.next:
print(temp.value, end="")
temp = temp.next
print(temp.value)
def add_num(self, num: str):
for item in num:
node = Node(item)
self.add(node)
if __name__ == '__main__':
num1 = '9999999999999'
num2 = '101010101'
l1 = Link()
l1.add_num(num1[::-1])
l1.show()
l2 = Link()
l2.add_num(num2[::-1])
l2.show()
# print(l1.root.value)
# print(l2.root.value)
# print(l1.length)
# print(l2.length)
def addTwoNumbers(l1: Link, l2: Link):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1.root and l2.root:
return l2
if not l2.root and l2.root:
return l1
if not (l1.root and l2.root):
print('滚开请不要玩了')
length = min((l1.length, l2.length))
temp1: Node = l1.root
temp2: Node = l2.root
next_add = 0
new_link = Link()
while length > 0:
total = int(temp1.value) + int(temp2.value)
if next_add > 0:
total += next_add
next_add, cur_num = get_div(total)
cur_node = Node(cur_num)
new_link.add(cur_node)
temp1 = temp1.next
temp2 = temp2.next
length -= 1
last_temp: Node = temp1 or temp2
# 处理链表剩余的元素
while next_add or last_temp:
while last_temp:
next_add, cur_num2 = get_div(int(last_temp.value) + next_add)
node = Node(cur_num2)
new_link.add(node)
# if not next_add:
# 这里我本来想如果next_add ==0的时候直接将,last_temp的next赋给new_list,但是Link中维持了一个length,这一样会让它出错,而且经过测试之后时间差不多所以就不改了
# new_link.add(last_temp.next)
# last_temp = None
# break
last_temp = last_temp.next
else:
if next_add:
node = Node(next_add)
new_link.add(node)
next_add = 0
new_link.show()
def get_div(total):
n, m = divmod(total, 10) # n是total//10取模的结果,m是total%10除数的结果
return n, m
start = time.time()
addTwoNumbers(l1, l2)
print(time.time() - start)