3 回答
TA贡献1877条经验 获得超1个赞
问题出现在您的第一个循环中:
while cur_node1.next is not None or cur_node2.next is not None:
这意味着两个节点之一可以具有next属性None。如果该节点的数据也小于另一个节点中的数据,则该节点变量将设置为None。然后while再次评估条件,并产生错误,因为该None值没有next属性......
cur_nodeX.next通过检查属性而None不是其本身,实际上使算法变得过于复杂cur_nodeX。因此,在第一个循环完成后,您仍然需要从两个列表中添加节点。此外,您的代码假设两个列表都不为空。
while因此,根据当前节点而不是它们的属性来设置条件next:
def merge(l1, l2):
cur_node1 = l1.head
cur_node2 = l2.head
l3 = LinkedList()
while cur_node1 is not None or cur_node2 is not None:
if cur_node1 is None or cur_node2 is not None and cur_node1.data > cur_node2.data:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
else:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
return l3
TA贡献1827条经验 获得超9个赞
对于任何想知道的人来说,这都是有效的。
def merge(l1, l2):
cur_node1 = l1.head
cur_node2 = l2.head
l3 = LinkedList()
while True:
if cur_node1 is None:
while cur_node2.next is not None:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
l3.append(cur_node2.data)
break
elif cur_node2 is None:
while cur_node1.next is not None:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
l3.append(cur_node1.data)
break
if cur_node1.data > cur_node2.data:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
elif cur_node1.data < cur_node2.data:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
return l3
TA贡献1784条经验 获得超8个赞
打印“1 -> 2 -> 12 -> 45 -> 69 -> 70 -> 99 -> 100”
def merge(l1, l2):
cur_node1 = l1.head
cur_node2 = l2.head
l3 = LinkedList()
while cur_node1 and (cur_node1.next is not None or cur_node2.next is not None):
if cur_node1.data > cur_node2.data:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
else:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
if cur_node1.next is None:
l3.append(cur_node1.data)
while cur_node2.next is not None:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
l3.append(cur_node2.data)
elif cur_node2.next is not None:
l3.append(cur_node2.data)
while cur_node1.next is not None:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
l3.append(cur_node1.data)
return l3
添加回答
举报