作业是通过交换节点而不是值来使用选择排序。当排序算法更改最后一个节点时,它会引发 AttributeError,因为
def min_sort()
中的first.next 似乎没有改变并且为 None。这是代码
class LinkedList:
class Node:
def __init__(self, data, next=None):
self.data, self.next = data, next
def __init__(self, seq):
self.front = self.Node(None)
curr = self.front
for value in seq:
curr.next = self.Node(value)
curr = curr.next
def swap(self, x, y):
first = self.front
while first.next is not None:
if first.next.data == x.data:
prevx = first
if first.next.data == y.data:
prevy = first
first = first.next
x, y = y, x
prevx.next, prevy.next = x, y
temp = x.next
x.next = y.next
y.next = temp
def progress(self, first, reverse):
try:
solid = first
while first.next is not None:
if solid.data > first.next.data and not reverse:
self.swap(solid, first.next)
elif solid.data < first.next.data and reverse:
self.swap(solid, first.next)
first = first.next
except Exception:
pass
def min_sort(self, reverse):
first = self.front
while first.next is not None:
self.progress(first, reverse)
first = first.next
def min_sort(seq, reverse=False):
ll = LinkedList(seq)
ll.min_sort(reverse)
return ll.get_list()
if __name__ == '__main__':
seq = (4, 30, 8, 31, 48, 19)
lst = min_sort(seq)
print(lst)
Traceback (most recent call last):
File "/Users/rival/My files/Škola/FMFI UK/2. semester/Programovanie 2/projekt8/riesenie.py", line 66, in <module>
lst = min_sort(seq)
^^^^^^^^^^^^^
File "/Users/rival/My files/Škola/FMFI UK/2. semester/Programovanie 2/projekt8/riesenie.py", line 60, in min_sort
ll.min_sort(reverse)
File "/Users/rival/My files/Škola/FMFI UK/2. semester/Programovanie 2/projekt8/riesenie.py", line 46, in min_sort
while first.next is not None:
^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'next'
我不知道如何更改函数中的引用
min_sort
所以它可以工作
错误是因为代码试图首先访问节点的first.next,而该节点为None。
您可以尝试添加额外的检查来处理这种情况
def min_sort(self, reverse):
first = self.front
while first is not None and first.next is not None:
self.progress(first, reverse)
first = first.next