检查链接列表是否加入以开始

sff*_*sff 6 java linked-list

我正在尝试检查链表的最后一个节点是否指向头部.此代码似乎为问题提供了积极的结果,但也为包含指向非头节点的节点的列表提供了误报.

我一直在尝试不同的事情,例如检查慢节点是否等于返回真实点的头部,但这似乎不起作用.

public boolean isLinkedToStart(Node head) {
    if (head == null) {
        return false;
    }
    Node fast = head.next;
    Node slow = head;
    while (fast != null && fast.next != null) {
        if (fast.next.next == slow) {
            return true;
        }
        fast = fast.next.next;
        slow = slow.next;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Cru*_*her 4

public boolean isLinkedToStart(Node head) {
    if (head == null) {
        return false;
    }
    Node fast = head.next;
    Node slow = head;
    while (fast != null && fast.next != null) {
        fast = fast.next.next;
        slow = slow.next;
        if(slow.next == head)
            return true;
        if (fast == slow)
            return false;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

好吧,第三次是一个魅力。

如果在 Slow 到达 head 之前找到了一个循环,那么我们就发现了一个不同的循环。如果缓慢使其达到头部,则循环就是头部。