繁体   English   中英

具有两个试图捕获循环的指针的链接列表

[英]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

可能性:

  1. 正如我上次建议的那样,使用某种类型的节点或路径禁用。 您的发布内容并未提及为何对您不起作用。
  2. 计算已执行的步骤数,并与节点总数(称为N)进行比较。 如果您走了n步却没有走到尽头,那么您就陷入了循环。
  3. 尝试构建一个新列表,其中包含从起点到最终节点的步骤。 这是严格线性的链表,例如START-> 3-> 6或START-> 1-> 2-> 3 ...如果您尝试添加此链表中已经存在的节点,则会出现循环。

由于步长不变,因此代码会更改,因此一旦它访问了节点两次,便会一次又一次地访问它。 这是由于这样的事实:它将在跟随重复节点的每个节点上做出相同的决策。 因此,您仅需检测(至少)一个节点是否已被访问两次。 以下是两种常见的实现方法:

  1. 计算链接列表中有多少个节点(即,获取一个新变量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
  1. 跟踪访问过的节点:为此,您只需向访问的每个节点添加一个新属性即可(即node.visited = True )。 在函数play的开始(即在初始循环中),您需要确保结构是干净的,即设置node.visited = False 如果您不希望在调用函数play之后更改节点,则可以在最后的另一个循环中删除它们(即del node.visited )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM