【发布时间】:2021-10-28 01:03:26
【问题描述】:
我在编译这个 mergesort linkedlist 时正在学习数据结构。我得到了这个错误。我尝试了很多但没有奏效。谁能告诉我出了什么问题?请。
Traceback(最近一次调用最后一次): 文件“C:\Users**\AppData\Local\Programs\Python\Python37\merge_sort_ver_2.0 链表.py”,第 122 行,在
sorted_list=merge_sort(lst)
文件“C:\Users**\AppData\Local\Programs\Python\Python37\merge_sort_ver_2.0 链表.py”,第 75 行,在 merge_sort 中
return merge(left,right)
文件“C:\Users**\AppData\Local\Programs\Python\Python37\merge_sort_ver_2.0 链表.py”,第 94 行,合并中
left_head=left.head
AttributeError: 'NoneType' 对象没有属性 'head'
def merge_sort(ll):
if ll.length()==1:
return ll
elif ll.head is None:
return ll
left_half,right_half=split(ll)
left=merge_sort(left_half)
right=merge_sort(right_half)
return merge(left,right)
def split(ll):
if ll.head==None or ll==None:
left_half=ll
right_half=None
return left_half,right_half
else:
size=ll.length()
mid=size//2
mid_node=ll.nodeAt(mid-1)
right_half=ll
left_half=LinkedList()
left_half.head=mid_node.next
mid_node.next=None
return left_half,right_half
def merge(left,right):
merged=LinkedList()
merged.tailinsert(0)
current=merged.head
left_head=left.head
right_head=right.head
while left_head or right_head:
if left_head is None:
current.next=right_head
right_head=right_head.next
elif right_head is None:
current.next=left_head
left_head=left_head.next
else:
merged.head=head
return merged.printlist()
lst=LinkedList()
lst.tailinsert(14)
lst.tailinsert(46)
lst.tailinsert(43)
lst.tailinsert(27)
sorted_list=merge_sort(lst)
print(sorted_list)
【问题讨论】:
-
错误很清楚地告诉你
left = None所以它不会有属性.head
标签: python attributeerror nonetype