[英]Linked list with two pointers trying to catch a loop
您好,我需要有关检测循环并在链表上返回False
帮助,但首先,让我解释一下此链表的外观:
这将是节点类:
class Node:
def __init__(self, next = None, stairs = None):
self.next = next
self.stairs = stairs
可能性:
由于步长不变,因此代码会更改,因此一旦它访问了节点两次,便会一次又一次地访问它。 这是由于这样的事实:它将在跟随重复节点的每个节点上做出相同的决策。 因此,您仅需检测(至少)一个节点是否已被访问两次。 以下是两种常见的实现方法:
N=0
并在play
功能的第一个循环的每次运行中将其递增)。 然后在第二个循环中计数已访问了多少个节点。 一旦这个数字大于N你知道至少有一个节点已经访问了至少两次,因此已经发现了一圈,需要break
跳出循环(或return
)。 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
node.visited = True
)。 在函数play
的开始(即在初始循环中),您需要确保结构是干净的,即设置node.visited = False
。 如果您不希望在调用函数play之后更改节点,则可以在最后的另一个循环中删除它们(即del node.visited
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.