首先,有一个简单的代码可以判断:
listnode_ptr current =head->next;
while(current)
{
if(current==head)
{
printf("YES!\n");
return 0;
}
else
{
current=current->next;
}
}
printf("NO!\n");
return 0;
但是,该代码的一个问题在于,它只适用于链表无环以及链表的尾接到了表头,即环的长度=链表长度,但如果链表的表尾接到了链表中间,它将陷入死循环,所以我们用两个指针p和q来完成,p每次移动一个结点,q每次移动两个结点,那么只要链表有环,q就会追上p,如果无环,那么q将指向表尾或者空。
listnode_ptr fast=head->next;
listnode_ptr slow=head;
while(fast)
{
if(fast==slow)
{
printf("YES!\n");
return 0;
}
else
{
fast=fast->next;
if(!fast)
{
printf("NO!\n");
return 0;
}
else
{
fast=fast->next;
slow=slow->next;
}
}
}
printf("NO!\n");
return 0;