判断链表是否有环
思路:
定义一个Fast结点一个Slow结点,Fast结点每次是Slow结点走的二倍,如果在Fast == NULL之前 Slow == Fast 就表明单链表带环
int HasListCircle(ListNode* pHead)//判断链表是否有环
{
assert(pHead);
ListNode* pFast = pHead;
ListNode* pSlow = pHead;
while (pFast && pFast->next)
{
pFast = pFast->next->next;
pSlow = pSlow->next;
if (pFast == pSlow)
return 1;
}
return 0;
}
求环长度
思路:先找到相遇点,记住相遇点,找一个节点从相遇点开始走,并记录走的结点个数,直到再次遇到相遇点,此时走过的节点个数就是环的长度
ListNode* GetMeetNode(ListNode* pHead)//求相遇点
{
assert(pHead);
ListNode* pFast = pHead;
ListNode* pSlow = pHead;
while (pFast && pFast->next)
{
pFast = pFast->next->next;
pSlow = pSlow->next;
if (pFast == pSlow)
return pFast;
}
return NULL;
}
int GetCircleLen(ListNode* pMeetNode)//求环的长度
{
ListNode* pCur = pMeetNode;
int count = 1;
if (pMeetNode == NULL)
return 0;
while (pCur->next != pMeetNode)
{
pCur = pCur->next;
count++;
}
return count;
}
求环的入口点
如图所示
ListNode* GetEnterNode(ListNode* pHead, ListNode* pMeetNode)//求环的入口
{
if (pHead == NULL || pMeetNode == NULL)
return NULL;
ListNode* pH = pHead;
ListNode* pM = pMeetNode;
while (pH != pM)
{
pH = pH->next;
pM = pM->next;
}
return pH;
}