Check if a singly linked list is cyclic

For a single table as follows, how do we determine whether it is a cycle or not.

write picture description here

We let the two pointers, the fast and slow pointers respectively, point to the head node, let the fast pointer move two nodes at a time, and the slow pointer move only one node at a time.

write picture description here

Since fast travels faster and slow travels slower, there must be a meeting node in the ring, then the length of the path traveled by slow is len + x, and the path traveled by fast is nR + len + x , n is the number of turns for fast, greater than or equal to 1; R is the length of the ring.
Since fast is twice as fast as slow, the path taken by fast is twice as long as slow.
Thus nR + len + x = 2len + 2x; thus, len = nR - x;
at this time, we will let the two pointers x and y start from the head node and the junction respectively, and the first encounter point will arrive The entry node of the ring.

write picture description here

Then the idea of ​​​​this algorithm is introduced here. We deduce len=nR-x, so that they must meet at the entry point.

//C实现代码
//判断是否成环,如果成环,返回环入口结点
Node * isCylization(Node * node){
    if(node == NULL) return NULL;
    Node * fast = node;
    Node * slow = node;
    while(1){
        fast = fast->next?fast->next:NULL;
        if(!fast)return NULL;
        fast = fast->next?fast->next:NULL;
        if(!fast)return NULL;
        slow = slow->next?slow->next:NULL;
        if(!slow)return NULL;
        if(slow == fast) break;
    }
    Node * x = node;
    Node * y = slow;
    for(;x == y;x=x->next;y=y->next);
    return x;
}
int main(){

    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325463160&siteId=291194637