思路:快慢指针思想
//判断单链表是否带环
SListNode* CheckCycle(SListNode* pHead)
{
SListNode* fast = pHead;
SListNode* slow = pHead;
while(fast&&fast->next)//快指针走两步,慢指针走一步,如果在同一个环中,一定相遇
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
{
return slow;
}
}
return NULL; //没有相遇
}
//若带环,求环的长度,
int LengthofCycle(SListNode* pHead, SListNode* pos)
{
int length = 0;
while (pHead!= pos&&pHead) //求环长度问题,可以转换为求头结点到相遇点之间的长度问题
{
pHead = pHead->next;
++length;
}
return length;
}
//求环的入口点
SListNode* FindEntry(SListNode* pHead)
{
assert(pHead);
SListNode* fast = pHead;
SListNode*slow = pHead;
while (fast&&fast->next) //让快指针追上慢指针
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
{
break;
}
}
fast = pHead; //再让快指针指向头结点
while (fast != slow) //两指针都走一步,当两指针在此相遇时,就是入口点
{
fast = fast->next;
slow = slow->next;
}
return fast;
}