首页 > 解决方案 > 为什么在以下代码中将值自动分配给 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具有Noneas value ,因此它将Nonevalue 分配给new变量。

因此,我预计会出现一个错误,即none type object has no attribute next,我没有得到。而这里的另一件事是while循环(while new)。在这里它应该为 new.next 分配一个新节点,然后以此类推,但是当我尝试打印它时,它说self.head.nextiealpha.next是 None 类型,因此退出了 while alpha 循环,我只在屏幕上打印了一个。我无法理解为什么new.next没有被分配node ("h")

标签: python

解决方案


您在开始时将self.headwhich is分配None给变量new,但在下一行中if self.head确保它不应该第一次运行。因为self.headisNone并且条件被评估为Falsewhile 循环将不会在第一次迭代中执行,并且在第二次迭代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.

推荐阅读