twk*_*nab 0 python linked-list
如果我创建了具有属性的节点的链接列表,是否可以使用while循环value打印value链接列表中所有节点的所有属性?
[编辑]另外,我如何调用iter魔术方法,以便我可以迭代并打印链表?我如何创建一个允许在某个对象的开头,结尾或之前或之后添加的方法?
(如果有一些基本的,在概念上,我在理解中遗漏了,我道歉)
下面是我设置的节点和单链表的代码,你会看到我打印了底部每个节点的每个值.但是,我不确定是否有一种简单的方法可以轻松打印所有值,而不是列出每个值:
# node class
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
# singly linked list class
class SinglyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
linked_list = SinglyLinkedList()
linked_list.head = Node('Alice')
linked_list.head.next = Node('Chad')
linked_list.head.next.next = Node('Debra')
print linked_list.head.value, linked_list.head.next.value, linked_list.head.next.next.value
# is there a way to print all values for `linked_list` easily?
Run Code Online (Sandbox Code Playgroud)
感谢Stack Community的帮助和阅读!
您可以使用while循环,首先将变量设置为头部,并在每次迭代时将下一个节点设置为:
node = linked_list.head
while node:
print node.value
node = node.next
Run Code Online (Sandbox Code Playgroud)
您的实施的一些其他建议:
1)不要list用作变量名.它是Python中的序列类型.
2)别忘了设置tail!
3)如果您想要花哨,可以__iter__在链表上实现以使其可迭代.您还可以实现一种add方法,以便更轻松地将新项目添加到列表中.这是一个示例实现:
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class SinglyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = linked_list.head
while node:
yield node
node = node.next
def add(self, node):
if self.head:
self.tail.next = node
else:
self.head = node
self.tail = node
linked_list = SinglyLinkedList()
linked_list.add(Node('Alice'))
linked_list.add(Node('Chad'))
linked_list.add(Node('Debra'))
print [node.value for node in linked_list] # ['Alice', 'Chad', 'Debra']
Run Code Online (Sandbox Code Playgroud)