在Python中迭代链接列表的问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Python中迭代链接列表的问题相关的知识,希望对你有一定的参考价值。
我试图在Python 3.7中从头开始实现链接列表,经过多次尝试,我似乎无法使用print_values()方法按预期的顺序打印所有节点值(顺序)。此时我不确定问题是使用append()方法还是print_values()方法。
class Node:
def __init__(self, node_value):
self.node_value = node_value
self.nextNode = None
class SinglyLinkedList:
# methods that should be available: get_size, insert_at, append, remove,
# update_node_value
def __init__(self):
self.head_node = None
self.tail_node = None
self.size = 0
def get_list_size(self):
"""This returns the value for the size variable which get incremented
every time a new node is added.
This implementation is better because it has a running time of O(1)
as opposed to iterating through the
whole list which has a running time of O(n)"""
return self.size
def append(self, value):
new_node = Node(value)
if self.head_node is None:
self.head_node = new_node
self.size += 1
else:
while self.head_node.nextNode is not None:
self.head_node = self.head_node.nextNode
self.head_node.nextNode = new_node
self.size += 1
def print_values(self):
current_node = self.head_node
list_values = []
while current_node.nextNode is not None:
list_values.append(current_node.node_value)
if current_node.nextNode.nextNode is None:
list_values.append(current_node.nextNode.node_value)
current_node = current_node.nextNode
if list_values is not None:
print("Linked list: " + str(list_values))
else:
print("Linked List is currently empty.")
# Helper code below.
new_ll = SinglyLinkedList()
new_ll.append("alpha")
print(new_ll.get_list_size())
new_ll.append("beta")
print(new_ll.get_list_size())
new_ll.append("gamma")
print(new_ll.get_list_size())
new_ll.append("delta")
print(new_ll.get_list_size())
new_ll.append("epsilon")
print(new_ll.get_list_size())
new_ll.append("zeta")
print(new_ll.get_list_size())
new_ll.print_values()
我输出的所有内容都是这样的:
1
2
3
4
5
6
Linked list: ['epsilon', 'zeta']
通常,单链表仅跟踪头部。 (也不是尾巴)。因此通常不使用self.tail_node = None
。
当使用linkedlist
或tree
时,它将使您的生活更容易使用递归而不是使用循环。如果您只想查看列表,循环工作正常,但如果您想更改它,那么我建议使用递归解决方案。
据说问题不在于你的print
与你的append
。
你永远不能移动头节点。你必须总是做一个指针,所以这导致了问题:
self.head_node = self.head_node.nextNode
固定:
def append(self, value):
new_node = Node(value)
if self.head_node is None:
self.head_node = new_node
self.size += 1
else:
temp_head = self.head_node
while temp_head.nextNode is not None:
temp_head = temp_head.nextNode
temp_head.nextNode = new_node
self.size += 1
递归解决方案:
def append(self, value):
new_node = Node(value)
self.size += 1
self.head_node = self.__recursive_append(self.head_node, new_node)
def __recursive_append(self, node, new_node):
if not node:
node = new_node
elif not node.nextNode:
node.nextNode = new_node
else:
node.nextNode = self.__recursive_append(node.nextNode, new_node)
return node
话虽如此,直到我重新打印你的打印之后我才意识到这一点,所以这里是一个更干净的打印方法,使用python生成器可以帮助你。
生成器是你可以使用python的东西,你通常不能与其他编程语言一起使用,它使得链接列表变成一个非常容易做到的值列表:
def print_values(self, reverse=False):
values = [val for val in self.__list_generator()]
if values:
print("Linked list: " + str(values))
else:
print("Linked List is currently empty.")
def __list_generator(self):
'''
A Generator remembers its state.
When `yield` is hit it will return like a `return` statement would
however the next time the method is called it will
start at the yield statment instead of starting at the beginning
of the method.
'''
cur_node = self.head_node
while cur_node != None:
yield cur_node.node_value # return the current node value
# Next time this method is called
# Go to the next node
cur_node = cur_node.nextNode
免责声明:生成器很好,但我只是这样做,以匹配你的方式(即从链表中获取一个列表)。如果列表不重要但你只想输出链表中的每个元素,那么我就是这样做的:
def print_values(self, reverse=False):
cur_node = self.head_node
if cur_node:
print('Linked list: ', end='')
while cur_node:
print("'{}' ".format(cur_node.node_value), end='')
cur_node = cur_node.nextNode
else:
print("Linked List is currently empty.")
我同意Error - Syntactical Remorse的答案,因为问题是附加的,而while循环的主体......这里是伪代码中的例子:
append 0:
head = alpha
append 1:
//skip the while loop
head = alpha
next = beta
append 2:
//one time through the while loop because next = beta
head = beta
//beta beta just got assigned to head, and beta doesn't have next yet...
next = gamma
append 3:
//head is beta, next is gamma...the linked list can only store 2 nodes
head = gamma //head gets next from itself
//then has no next
next = delta
...etc.
以上是关于在Python中迭代链接列表的问题的主要内容,如果未能解决你的问题,请参考以下文章