“'self.head'”在单个 link 列表中的状态

Status of ''self.head'' in a singly link list

我一直在练习 link 列表,但无法理解“'self.head'”的实际含义。 它是索引 0 处列表中的第一个值吗?我怎样才能在头部打印数据?

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


class Linkedlist:
    def __init__(self):
        self.head = None
    def print_var(self):
        itr = self.head
        print(itr.data)
def insert_at_begining(self, data):
    node = Node(data, self.head)
    self.head = node
if __name__ = '__main__':
ll = Linkedlsit()
ll.insert_at_begining(3)
ll.insert_at_begining(4)
ll.insert_at_begining(6)
ll.insert_at_begining(8)
ll.print()

如果我要调用打印函数,它会出错。 (比如,link列表不为空)

self.head 指的是列表中的第一个 Node。从那里,您可以使用以下内容“遍历”列表:

current_node = ll.head
while current_node:
    print(f"Current node data: {current_node.data}")
    current_node = current_node.next

print("Reached End of List")

查看我的代码和相关评论

ll = LinkedList() # Create empty list
print(ll.head) # This prints None, because the list is empty, there are no nodes
ll.print_var() # This gives you an error. You're trying to print ll.head.data, but as shown before ll.head is None, not a Node
ll.head = Node('hello', ll.head) # The list now has one node
ll.print_var() # This is now working, and prints 'hello'