您的位置:首页 > 编程语言 > C语言/C++

判断单链表是否带环?若带环,求环的长度?求环的入口点?(C语言)

2016-04-14 20:03 483 查看
PSListNode HasCycle(PSListNode pHead)
{
if ((NULL == pHead) || (NULL == pHead->pNextNode))
{
return NULL;
}
else
{
PSListNode pFast = pHead->pNextNode->pNextNode;
PSListNode pSlow = pHead->pNextNode;
//利用快慢指针,让快指针每次走两步,慢指针每次走一步,要是快指针没有走到NULL,且快指针与慢指针指向相同就说明是有环
while (pFast != pSlow)
{
//快指针要是没有指向为空,那么慢指针就不可能指向空(快指针走得快)
if (NULL == pFast)
{
return;
}
else
{
pFast = pFast->pNextNode;
pSlow = pSlow->pNextNode;
if (NULL == pFast)
{
return;
}
else
{
pFast = pFast->pNextNode;
}
}
}
return pFast;
}
}

int GetCyleLen(PSListNode pMeetNode)
{
//默认传的参数是HasCycle函数返回的环中的一个结点
if (NULL == pMeetNode)
{
return 0;
}
else
{
int nCount = 1;
PSListNode pNode = pMeetNode;
while (pMeetNode != pNode->pNextNode)
{
pNode = pNode->pNextNode;
nCount++;
}
return nCount;
}
}
//pMeetNode参数是用HasCycle函数求链表是否有环时pFast指针与pSlow指针的碰撞点
//定律:在链表头,pFast指针与pSlow指针的碰撞点分别设定一个指针,每次各走一步,两个指针必定相遇,则相遇第一点为环入口点
PSListNode FindEnterNode(PSListNode pHead, PSListNode pMeetNode)
{
PSListNode pNode = pHead;
if ((NULL == pHead) || (NULL == pMeetNode))
{
return NULL;
}
while (pNode != pMeetNode)
{
pNode = pNode->pNextNode;
pMeetNode = pMeetNode->pNextNode;
}
return pNode;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: