删除整个链表时使用" delete_whole (self)">方法。它抛出no attribute错误. 尽管上面的代码运行良好。它不是打印空白列表,而是给出no attribute错误。
class Node:
def __init__(self,value):
self.value = value
self.next = None
class CircularSinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while True:
yield node
if node.next is self.head:
break
node = node.next
def insertion(self, value, location):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.tail = new_node
self.tail.next = self.head
else:
if location == 0:
new_node.next = self.head
self.head = new_node
self.tail.next = new_node
elif location == -1:
self.tail.next = new_node
new_node.next = self.head
self.tail = new_node
else:
temp_node = self.head
index = 0
while index < location -1:
if temp_node.next is self.head:
break
temp_node = temp_node.next
index += 1
next_node = temp_node.next
temp_node.next = new_node
new_node.next = next_node
if new_node.next is self.head:
self.tail = new_node
#---------------------------------------------------------------------------------------------#
# deleting the entire linked list
def delete_entire(self):
self.head = None
self.tail.next = None
self.tail = None
cll = CircularSinglyLinkedList()
cll.insertion(2,1)
cll.insertion(3,2)
cll.insertion(5,3)
cll.insertion(6,4)
cll.insertion(0,0)
cll.insertion(10,-1)
print([node.value for node in call])
output = [0,2,3,5,6,10]
cll.delete_entire()
print([node.value for node in call])
AttributeError: 'NoneType'对象没有属性'value'
期望输出为
[]
您的__iter__()
方法总是产生一次,即使列表为空,因为它在检查node
是否为None
之前执行yield node
。当列表为空时,将产生None
,调用者将尝试使用None.value
。
当node
变为None
时,应立即停止循环。
def __iter__(self):
node = self.head
while node:
yield node
node = node.next