原文:https://blog.csdn.net/caoshangpa/article/details/80363335
思想:快慢指针法。快指针的步长是2,慢指针的步长是1,若相遇,则必有环。
int hasCycle(ListNode *head)
{
ListNode *fast,*slow;
if(NULL==head)
{
return 0;
}
fast=head;
slow=head;
if(NULL!=fast && NULL!=fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
{
return 1;
}
}
return 0;
}
环长计算思想:快慢指针从第一次重合到第二次重合,慢指针的步长为环的长度。
int GetLoopLength(Node* head)
{
Node *slow = head, *fast = head;
while ( fast && fast->next )
{
slow = slow->next;
fast = fast->next->next;
if ( slow == fast )//第一次相遇
break;
}
slow = slow->next;
fast = fast->next->next;
int length = 1; //环长度
while ( fast != slow )//再次相遇
{
slow = slow->next;
fast = fast->next->next;
length ++; //累加
}
return length;
}