简体   繁体   English

返回循环链表Java的开始

[英]Returning start of a circularly linked list Java

So I'm working through interview problems, and I'm given the following: 所以我正在处理面试问题,我给出了以下内容:

/** Give a circularly linked list, implement an algorithm which returns
 *  the node at the beginning of the loop. */

I've seen the fastrunner & slowrunner / tortoise & hare method with two pointers and some clever math to find the beginning node, but I just came up with the following solution, and am wondering if theres anything wrong with it or any criticism you guys can see in comparison to the usual method of solving this. 我已经看到了带有两个指针和一些聪明的数学的fastrunner&slowrunner / tortoise&hare方法来找到起始节点,但我想出了以下解决方案,并且想知道它是否有任何问题或任何批评你们可以看出与通常的解决方法相比。 It seems too easy to me, but it makes sense that it would work: Just go through the list, and if you ever hit a node that you've previously seen, that means you're at the start of your loop. 这对我来说似乎太容易了,但它有效是有意义的:只需浏览一下列表,如果你曾经遇到过你之前看过的节点,那就意味着你处于循环的开始阶段。

/** Give a circularly linked list, implement an algorithm which returns
 *  the node at the beginning of the loop. */
public static Node firstInLoop(Node n) {
    HashSet<Node> visited = new HashSet<>();
    while (n != null) {
        if (visited.contains(n)) {
            return n;
        } else {
            visited.add(n);
            n = n.tail;
        }
    }
    return null;
}

乌龟和野兔方法使用O(1)内存和O(n)时间,而你的算法使用O(n)内存和O(n)时间,但可能使用较小的常数因子。

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

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