我有一个关于学校的链接列表分配,虽然我只是得到了类构造函数。我试图简单地了解链表数据结构的基础知识,并且我理解基本概念。我已经看了很多Youtube教程等,但是我无法理解的是如何使用循环打印出节点中的货物或数据。
我写过这些内容:
class Node:
def __init__(self, value, pointer):
self.value = value
self.pointer = pointer
node4 = Node(31, None)
node3 = Node(37, None)
node2 = Node(62, None)
node1 = Node(23, None)
现在......我明白每个节点声明都是对Node的类构造函数的调用,并且列表是链接的,因为每个节点都包含指向下一个节点的指针,但我根本不明白如何打印它们使用循环。我已经看到了使用全局变量作为“head”的示例,并且我已经看到为完成任务而创建的子类。我老了又傻了。我想知道是否有人可以放慢速度并向我解释,就像我是5.如果那里的任何人有同情和愿意牵着我的手解释,我将非常感激。先谢谢你,亲切的先生。
答案 0 :(得分:0)
首先,您的节点应该像这样创建:
node4 = Node(31, node3)
node3 = Node(37, node2)
node2 = Node(62, node1)
node1 = Node(23, None)
现在,我确信您可以看到列表中的最后一个节点将指向“无”。因此,您可以遍历列表,直到遇到无。这样的事情应该有效:
printhead = node4
while True:
print(printhead.value)
if printhead.pointer is None:
break;
else :
printhead = printhead.pointer
答案 1 :(得分:0)
这是一个非常基本的链接列表实现,仅用于教育目的。
from __future__ import print_function
"""The above is needed for Python 2.x unless you change
`print(node.value)` into `print node.value`"""
class Node(object):
"""This class represents list item (node)"""
def __init__(self, value, next_node):
"""Store item value and pointer to the next node"""
self.value = value
self.next_node = next_node
class LinkedList(object):
"""This class represents linked list"""
def __init__(self, *values):
"""Create nodes and store reference to the first node"""
node = None
# Create nodes in reversed order as each node needs to store reference to next node
for value in reversed(values):
node = Node(value, node)
self.first_node = node
# Initialize current_node for iterator
self.current_node = self.first_node
def __iter__(self):
"""Tell Python that this class is iterable"""
return self
def __next__(self):
"""Return next node from the linked list"""
# If previous call marked iteration as done, let's really finish it
if isinstance(self.current_node, StopIteration):
stop_iteration = self.current_node
# Reset current_node back to reference first_node
self.current_node = self.first_node
# Raise StopIteration to exit for loop
raise stop_iteration
# Take the current_node into local variable
node = self.current_node
# If next_node is None, then the current_node is the last one, let's mark this with StopIteration instance
if node.next_node is None:
self.current_node = StopIteration()
else:
# Put next_node reference into current_node
self.current_node = self.current_node.next_node
return node
linked_list = LinkedList(31, 37, 62, 23)
for node in linked_list:
print(node.value)
这并没有正确处理很多情况(包括循环体中的 break 语句),但目标是显示Python中链表实现的最低要求。