【发布时间】:2021-04-07 07:06:26
【问题描述】:
我实现了一个链表。现在我应该对两个链表的每个对应项求和。
这是链表的实现
class Node:
def __init__(self, data=0, next_node=None):
self.data = data
self.next_node = next_node
class LinkedList:
def __init__(self):
self.head = None
def __iter__(self):
current = self.head
while current is not None:
yield current.data
current = current.next_node
def add_last(self, node):
if self.head is None:
self.head = node
return
current = self.head
while current.next_node:
current = current.next_node
current.next_node = node
但是当我对每个链表的项目求和时,我有一个无限循环并且我的链表没有迭代
这是求和过程
def two_sum(list1: LinkedList, list2: LinkedList) -> LinkedList:
l1 = list1.head
l2 = list2.head
res_list = LinkedList()
carry = 0
while l1 is not None or l2 is not None:
x = l1.data if l1 else 0
y = l2.data if l2 else 0
sum = carry + x + y
res_list.add_last(Node(sum % 10))
carry = carry // 10
l1 = l1.next_node if l1.next_node else l1
l2 = l2.next_node if l2.next_node else l2
if carry > 0:
res_list.add_last(Node(carry))
return res_list
【问题讨论】:
-
你不会从下一个节点前进,所以你永远不会到达最后的
None。while循环中的最后两行应该是lx = lx.next_node if lx else lx或者可能是if lx: lx = lx.next_node。
标签: python algorithm linked-list