【发布时间】:2020-06-18 14:28:31
【问题描述】:
我正在尝试在 Python 中合并两个链表,但每次我收到错误:类型对象 'List' 显然具有合并功能时没有属性 'merge'。
示例输入:
8 11 20 24 50
5 9 10 30 33 40 45
样本输出:
5 8 9 10 11 20 24 30 33 40 45 50
class Node:
def __init__ (self, data):
self.data = data
self.next = None
class List:
def __init__(self):
self.head = None
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def merge(head1, head2):
temp = None
if head1 is None:
return head2
if head2 is None:
return head1
if head1.data <= head2.data:
temp = head1
temp.next = merge(head1.next, head2)
else:
temp = head2
temp.next = merge(head1, head2.next)
return temp
接受输入:
inp = [int(i) for i in input().split(" ")]
inp2 = [int(i) for i in input().split(" ")]
l = List()
l2 = List()
for i in inp:
l.append(i)
for i in inp2:
l2.append(i)
rez = List.merge(l, l2)
print(rez)
感谢您的宝贵时间!
【问题讨论】:
-
也许你离开了
@static_method装饰器?merge当前是实例方法,而不是类方法(尽管您将self保留为第一个参数) -
merge()的参数应该是Lists 还是Nodes?你的称呼不一致。 -
我看不出这段代码是如何产生这个错误的。在您的真实代码中,
merge()函数是否缩进在List类下面? -
当我运行你的代码时,我得到一个不同的错误 btw
AttributeError: 'List' object has no attribute 'data'这是正确的,因为.data在你的Node类上,但if head1.data <= head2.data:你正在混淆节点和列表。我建议您开始使用类型提示来使您的代码更清晰。如果这样做,您会发现List是一个错误的名称选择,因为它已被typing模块采用 -
请编辑问题以包含完整的错误回溯消息。