Python 为什么在堆栈类中将linkedlist应用于pop函数时会出现这种类型的错误
我不知道为什么在运行pop时获取AttributeError:'NoneType'对象没有属性'data'Python 为什么在堆栈类中将linkedlist应用于pop函数时会出现这种类型的错误,python,Python,我不知道为什么在运行pop时获取AttributeError:'NoneType'对象没有属性'data' class PersonNode: def __init__(self, d=None, next=None): self.data = d self.next = next class stack: def __init__(self): self.top = None
class PersonNode:
def __init__(self, d=None, next=None):
self.data = d
self.next = next
class stack:
def __init__(self):
self.top = None
def push(self,p):
new_node = PersonNode(p)
if self.top == None:
self.top = new_node
else:
new_node.next = self.top
self.top = new_node
def pop(self):
# if self.top != None:
# print("{0} is popped successfully".format(self.top.data))
#self.top = self.top.next
curr_node = self.top
while curr_node != None:
curr_node = curr_node.next
#self.top = curr_node.next
print(curr_node.data, "is popped successfully")
改变
到
请注意,如果堆栈为空,并且您试图弹出某些内容,则仍会出现错误。您将首先分配下一个节点,然后打印弹出的元素。您真正应该做的是首先打印值,然后移动到下一个节点。之后,您将有一个
while
,它将注意下一个节点是否为空
按以下方式更改您的pop
:
def pop(自):
如果self.top:
curr_node=self.top
而当前节点:
打印(curr_node.data,“弹出成功”)
curr\u node=curr\u node.next
其他:
打印(“堆栈为空!”)
因为您在转到下一个节点后尝试访问curr\u node.data
,但尚未测试它是否为无。只需反转最后两行。我这样做了,但现在while循环无限期地保持,如何在最后一项之后使curr_node=None来中断循环?这就是我调用函数的方式:while(stack.top!=None):stack.pop()我这样做了,但仍然无法退出循环,我怎么解决呢?噢,天哪,我忘了一些重要的事情。检查编辑后的答案。功能仍然没有退出循环,如何中断循环?您可以共享测试数据吗?功能仍然没有退出循环,如何中断循环?
while curr_node != None:
curr_node = curr_node.next
#self.top = curr_node.next
print(curr_node.data, "is popped successfully")
while curr_node.next != None:
curr_node = curr_node.next
print(curr_node.data, "is popped successfully")