利用快慢指针:
fast快指针每次移动两个位置;slow慢指针每次移动一个位置;
如果链表有环的话 快慢指针一定会相遇。
链表:L(头结点) → 1 → 2 → 3 → 2(环在 2、3 之间) 初始 slow=1,fast=1
- slow=2,fast=3;slow≠fast,继续
- slow=3,fast=2;slow≠fast,继续
- slow=2,fast=2;slow == fast → return 1,判定有环。
int hasCycle_Head(LinkList L)
{
if(L==NULL || L->next==NULL)
return 0;
LNode*fast=L->next;
LNode*slow=L->next;
while(fast != NULL || fast->next != NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
return 1;
}
}
return 0;
}