方法一
使用p、q两个指针,p总是向前走,但q每次都从头开始走,对于每个节点,看p走的步数是否和q一样。
int way_1(linklist* head)//头结点的地址
{
if(head->next==NULL)//如果只有头结点,直接结束
return 0;
linklist* p = head;
int count_p = 0;
while (p != NULL)
{
linklist* q = head;
int count_q = 0;
while (p != NULL)
{
if (p == q)//当指向结点相同时
{
if (count_q == count_p)//并且步数一样,说明,没有遇到环
break;
else//步数不同,但是指向结点相同,说明有环
return 1;
}
count_q++;
}
count_p++;
q = q->next;
}
return 0;
}
方法二
使用slow、fast两个指针,slow每次向前走一步,fast每次向前走两步,若在某个时候fast==slow,则存在环。
int way_2(linklist* head)
{
if (head->next == NULL)
return 0;
linklist* slow = head;
linklist* fast = head;
while (fast != NULL && fast->next != NULL)
{
fast = fast->next->next;//每次走两步
slow = slow->next;//每次走一步
if (fast == slow)
return 1;
}
return 0;
}