我想使用以下代码在python中合并2个排序的链表:
def merge_lists(h1, h2):
if h1 is None:
return h2
if h2 is None:
return h1
if (h1.value < h2.value):
h1.next = merge_lists(h1.next, h2)
return h1
else:
h2.next = merge_lists(h2.next, h1)
return h2
h1=[1,5,7]
h2=[2,4,6]
print (type(h1))
merge_lists(h1, h2)
我收到以下错误:
<class 'list'>
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-38-2f8d8dee291e> in <module>()
17 print (type(h1))
18
---> 19 merge_lists(h1, h2)
<ipython-input-38-2f8d8dee291e> in merge_lists(h1, h2)
5 return h1
6
----> 7 if (h1.value < h2.value):
8 h1.next = merge_lists(h1.next, h2)
9 return h1
AttributeError: 'list' object has no attribute 'value'
答案 0 :(得分:2)
逻辑很好,但是您在关于如何表达要执行的列表操作的假设(错误的)。
def merge_lists(h1, h2):
if h1 == []:
return h2
if h2 == []:
return h1
if (h1[0] < h2[0]):
return h1[0:1] + merge_lists(h1[1:], h2)
else:
return h2[0:1] + merge_lists(h1, h2[1:])
答案 1 :(得分:1)
为什么不使用Python标准逻辑:
sorted(h1 + h2)