Python 非类型没有属性';下一个';在链表中
我被卡住了,我看不出我的代码有什么问题。这是:Python 非类型没有属性';下一个';在链表中,python,linked-list,Python,Linked List,我被卡住了,我看不出我的代码有什么问题。这是: class Node : def __init__(self,data=0,next=None): self.data = data self.next = next class LinkedList: def __init__(self,head=None): self.head = head def append(self,data): new_Node = Node(data) if
class Node :
def __init__(self,data=0,next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self,head=None):
self.head = head
def append(self,data):
new_Node = Node(data)
if (self.head):
cons = self.head
while(cons):
cons = cons.next
cons.next = new_Node
else:
self.head = new_Node
def printt(self):
cons = self.head
while(cons):
print(cons.data)
cons = cons.next
Q = LinkedList()
Q.append(3)
Q.append(4)
Q.printt()
错误消息是
Traceback (most recent call last):
File "/tmp/sessions/18c2fb2c9abeb710/main.py", line 26, in <module>
Q.append(4)
File "/tmp/sessions/18c2fb2c9abeb710/main.py", line 16, in append
cons.next = new_Node
AttributeError: 'NoneType' object has no attribute 'next'
回溯(最近一次呼叫最后一次):
文件“/tmp/sessions/18c2fb2c9abeb710/main.py”,第26行,在
问题(4)
文件“/tmp/sessions/18c2fb2c9abeb710/main.py”,第16行,在附录中
cons.next=新节点
AttributeError:“非类型”对象没有属性“下一个”
我试图纠正错误,但未能解决。
您能帮忙吗?您只需更改线路即可:
while(cons):
while(cons):
到-
否则,当您离开循环时,
cons
已经是None
。行中出现错误:
while(cons):
while(cons):
当cons时必须停止。next
为None。在您的情况下,代码将一直运行,直到cons
变为None
。然后在下一行,您有语句cons.next=new_Node
,它基本上检查None.next
,从而检查错误
因此,使用cons.next
而不仅仅是cons
。以下各项可以正常工作:
class Node :
def __init__(self,data=0,next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self,head=None):
self.head = head
def append(self,data):
new_Node = Node(data)
if (self.head):
cons = self.head
while(cons.next):
cons = cons.next
cons.next = new_Node
else:
self.head = new_Node
def printt(self):
cons = self.head
while(cons):
print(cons.data)
cons = cons.next
Q = LinkedList()
Q.append(3)
Q.append(4)
Q.printt()
**-----------------非常感谢-----------------**