'的状态'self.head''在单个链接列表中



我一直在练习链表,但不明白"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()

如果我要调用打印函数,它将通过一个错误。(比如,链表不是空的(

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'

最新更新