python - 为什么在以下代码中将值自动分配给 new_element
问题描述
class node:
def __init__(self,data):
self.data = data
self.next = None
class ll():
def __init__(self):
self.head = None
def append(self,*argv):
for data in argv:
new = self.head
if self.head:
while new:
new = new.next
new = node(data)
else:
self.head = node(data)
def read(self):
alpha = self.head
while alpha:
print(alpha.data)
alpha = alpha.next
def main():
a = ll()
a.append("a","h","j","k")
a.read()
if __name__ == "__main__":
main()
问题1:
最初self.head
具有None
as value ,因此它将None
value 分配给new
变量。
因此,我预计会出现一个错误,即none type object has no attribute next,我没有得到。而这里的另一件事是while循环(while new)。在这里它应该为 new.next 分配一个新节点,然后以此类推,但是当我尝试打印它时,它说self.head.next
iealpha.next
是 None 类型,因此退出了 while alpha 循环,我只在屏幕上打印了一个。我无法理解为什么new.next
没有被分配node ("h")
解决方案
您在开始时将self.head
which is分配None
给变量new
,但在下一行中if self.head
确保它不应该第一次运行。因为self.head
isNone
并且条件被评估为False
while 循环将不会在第一次迭代中执行,并且在第二次迭代new
中将具有有效的非无值。
遇到第二个问题,您必须将 while 循环更改为以下以获得所有结果:
if self.head:
while new.next: # We have to stop when after a node there is None.
new = new.next
new.next = node(data) # Now add the new data at the end.
推荐阅读
- python - 使用 softmax(1D Array 到 2D Array)在 AI 上测试数据
- google-cloud-platform - 在 BigQuery 中使用 EXCEPT 关键字和非表值
- javascript - 将 useRef 与旧版本的反应组件一起使用?
- python - Django 搜索表单,消歧页面
- r - 在R中制作地图的困难
- javascript - 如何在 AMD 模块系统中使用 tsify 生成捆绑文件,而不是单独的文件或使用未找到的“定义”的文件?
- amazon-web-services - 如何从 Linux 机器上的 Web 浏览器访问 AWS EC2 实例?
- tfs - 从外部执行 tfs get 时 TFS 无法指定工作区
- stanford-nlp - 如何使用 NLP Java 提取主语动词对象?对于每一句话
- javascript - 使用时无法向集群添加令牌