Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if Linked List joins back to start

I'm trying to check if the last node of a linked list points to the head. This code seems to give a positive result for the problem, but also gives a false positive for a list that contains a node pointing to a non-head node.

I've been trying different things such as checking if the slow node is equal to the head at the return true point, but that doesn't seem to work.

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;
}

Any suggestions?

like image 836
sff Avatar asked Oct 18 '13 18:10

sff


1 Answers

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;
}

Okay, third time is a charm.

If a cycle is found before slow makes it way to head, then we found a different cycle. If slow makes it to head, then the cycle is to head.

like image 173
Cruncher Avatar answered Oct 04 '22 03:10

Cruncher