Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/nginx/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-链表-追加_Python_Python 3.x_Linked List - Fatal编程技术网

Python-链表-追加

Python-链表-追加,python,python-3.x,linked-list,Python,Python 3.x,Linked List,我正试图学习python中的链表,我被赋予了链表类并被要求创建append方法 下面是提供的代码 class Node: def __init__(self, item, next): self.item = item self.next = next class LinkedList: def __init__(self): self.head = None def add(self, item): s

我正试图学习python中的链表,我被赋予了链表类并被要求创建append方法

下面是提供的代码

class Node:
    def __init__(self, item, next):
        self.item = item
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self, item):
        self.head = Node(item, self.head)

    def remove(self):
        if self.is_empty():
            return None
        else:
            item = self.head.item
            self.head = self.head.next
            return item

    def is_empty(self):
        return self.head == None

    def __str__(self):
        tmp_str = ""
        ptr = self.head
        while ptr != None:
            tmp_str += ptr.item + " "
            ptr = ptr.next

        return tmp_str
这是我的append方法,但它有问题。我知道如果链表是空的,我必须创建一个链表,当链表中有元素时问题就开始了

def append(self, item):
    ptr = self.head
    if ptr:
        while ptr != None:
            ptr = ptr.next
        ptr = Node(item, ptr)
    else:
        self.head = Node(item, self.head)

谁能告诉我我做错了什么?非常感谢任何帮助。

进行两次检查-第一次检查self.head是否已初始化。第二个节点应该遍历列表,直到找到最后一个节点。确保没有超出边界,否则将无法将最后一个节点链接到新的最后一个节点

def append(self, item):
    if not self.head:
        self.head = Node(item, self.head)
    else:
        ptr = self.head
        while ptr.next:                    # traverse until ptr.next is None
            ptr = ptr.next
        ptr.next = Node(item, ptr.next)    # initialise ptr.next

如果
ptr
不是
None
(即,在列表非空的情况下),找到列表中的最后一个节点,然后可以执行
last.next=node(item,None)
术语挑剔:
append
不是类,而是函数,你的
LinkedList
类的一个方法。@juanpa.arrivillaga谢谢我修正了it@OmOWalker差不多。如果您到达
ptr
为None的点,并分配
ptr
,这并不意味着您正在重新分配尾部的下一个属性!我希望这能帮你解决问题。是的,我会继续练习:D.给你投票,但这说明我名声不好。