链接列表在2个节点后停止,为什么?

问题描述 投票:0回答:1

第一篇文章。我正在尝试使用下面的代码实现链表,但是以某种方式链表将在第二个节点之后停止。我期望9-> 6-> 11-> 8-> 15-> 19-> 7->,但是我只有9-> 6->。谁能帮我弄清楚我的代码有什么问题?谢谢!

class Node:
    def __init__(self,value):
        self.next = None
        self.val = value
    def __str__(self):
        return str(self.val)

class SLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
    def append_node(self,value):
        if self.head == None:
            self.head = self.tail = Node(value)  
        else:
            self.tail.next = Node(value)
            self.tail = Node(value)
        return self


llist = SLinkedList()
llist.append_node(9).append_node(6).append_node(11) \
.append_node(8).append_node(15).append_node(19) \
.append_node(7)  

print(llist.head.next.next) # returned None. Why??
python linked-list singly-linked-list
1个回答
0
投票

如果将self.tail = Node(value)替换为self.tail = self.tail.next,它将起作用。

© www.soinside.com 2019 - 2024. All rights reserved.