def play(first, step):
'''(LinkedList, int) -> bool
'''
# locates the end_node
end_list = first
found = False
# Used to find Node population
N = 0
while end_list.next != None and found != True:
if end_list.next == first:
found = True
else:
end_list = end_list.next
N = N + 1
stepcount = 1
count = 1
current = first
winner = False
loop = False
# Goes through the linked list
while current != None and winner != True and loop != True:
# If count == step, then we check if we are at the last square or
# else if we are on a stairs then we may use them.
# If none of them are found then we itterate normally making count back to 1.
# If stepcount passes the overall N (population of all the nodes), then it will detect a loop
if stepcount > N:
loop = True #one node has been visited more than once so there is a loop
elif count == step:
if current == end_list:
winner = True
elif current.stairs:
current = current.stairs
count = 0
else:
current = current.next
count = 0
stepcount = stepcount + 1
else:
current = current.next
count = count + 1
return current == end_list
因为你的步长不会改变代码,一旦它访问了一个节点两次,就会一遍又一遍地访问它。这是因为它将在重复节点之后的每个节点上做出相同的决定。因此,您只需要检测是否(至少)有一个节点被访问了两次。两种常见的方法是:
N=0
,并在每次运行play
函数的第一个循环时递增它)。然后在第二个循环中计算访问了多少个节点。一旦这个数字大于N,您就知道至少有一个节点被访问了至少两次,因此您检测到一个圆,需要break
退出循环(或return
)。在node.visited = True
)。在函数play
的开始(即在初始循环中),您需要确保结构是干净的,即setnode.visited = False
。如果您不想在函数play被调用后更改节点,那么可以在末尾的另一个循环中删除它们(即del node.visited
)。在可能性:
相关问题 更多 >
编程相关推荐