首先上代碼(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; } } }
假設(shè)環(huán)的長度為d,A點(diǎn)位鏈表的第一個(gè)節(jié)點(diǎn),B點(diǎn)為環(huán)入口點(diǎn),C點(diǎn)為第一次相遇點(diǎn); 現(xiàn)在假設(shè)有x和y兩人從A點(diǎn)出發(fā),設(shè)x的速度為v,y的速度為2v, 所以再C點(diǎn)x走的長度為|AB|+|BC|,y走的長度為|AB|+|BC|+nd (n為y走的圈數(shù)) 所以有(|AB|+|BC| +nd)/2v = (|AB|+|BC|)/v 化簡得|AB| = nd - |BC| 所以當(dāng)x和y以相同的速度v重新從A點(diǎn)和C點(diǎn)出發(fā),當(dāng)x走到B點(diǎn)時(shí),y距離走n圈(n為整數(shù))還差|BC|,而y的起點(diǎn)為C點(diǎn),所以其整數(shù)圈均在C點(diǎn);所以他們相遇在B點(diǎn)即入環(huán)點(diǎn)。 |
|