首先上代码(c代码)
void pListFirstRingNode(pList *pHead)
{
pList pFast = *pHead;
pList pSlow = *pHead;
pList pTmp = NULL;
while (1)
{
pFast = pFast->_pNext->_pNext;
pSlow = pSlow->_pNext;
if (pFast == pSlow)
{
pTmp = pFast;
break;
}
}
pSlow = *pHead;
while (1)
{
pTmp = pTmp->_pNext;
pSlow = pSlow->_pNext;
if (pSlow = pTmp)
{
printf("The entry point is%p and is vale is %d\n", pSlow, pSlow->data);
return;
}
}
}
假设环的长度为d,A点位链表的第一个节点,B点为环入口点,C点为第一次相遇点;
现在假设有x和y两人从A点出发,设x的速度为v,y的速度为2v,
所以再C点x走的长度为|AB|+|BC|,y走的长度为|AB|+|BC|+nd (n为y走的圈数)
所以有(|AB|+|BC| +nd)/2v = (|AB|+|BC|)/v 化简得|AB| = nd - |BC|
所以当x和y一相同的速度v重新从A点和C点出发,当x走到B点时,y距离走n圈(n为整数)还差|BC|,而y的起点为C点,所以其整数圈均在C点;所以他们相遇在B点即入环点。