题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
解答
脑子里总想起来一个解答但是忘了怎么写。
https://blog.csdn.net/qq_38790716/article/details/89207822
这边除了有代码解答还有数学证明。
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
//先利用两个指针判断链表是否有环
ListNode* pFast = pHead;
ListNode* pSlow = pHead;
while(pFast!= NULL && pFast->next!=NULL ){
pFast = pFast->next->next; //快指针走两步
pSlow = pSlow->next;
if(pFast == pSlow)
break;
}
if(pFast==NULL || pFast->next==NULL)
return NULL; //没有环
//确定有环,在让快指针从头走环外距离,就能到环入口
pFast = pHead;
while(pFast!=pSlow){
pFast=pFast->next;
pSlow=pSlow->next;
}
return pFast;
}
};