题目:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
A:创建两个指针,一个pFast一个pSlow指向链头,pFast一次走2步,pSlow一次走1步,如果两个指针必相遇,则链表有环
把其中一个指针指向链表头部,另一个指针位置不变(它还在环内),两个指针每次各走1步,直到相遇的地方就是环的入口结点
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode* pFast = pHead;
ListNode* pSlow = pHead;
while ((pFast != nullptr) && (pFast->next != nullptr) && (pSlow != nullptr))
{
pFast = pFast->next->next;
pSlow = pSlow->next;
if (pFast == pSlow)
{
break;
}
}
if ((pFast == nullptr) || (pFast->next == nullptr) || (pSlow == nullptr))
{
return nullptr;
}
pFast = pHead;
while (pFast != pSlow)
{
pFast = pFast->next;
pSlow = pSlow->next;
}
return pFast;
}
};

原文:https://www.cnblogs.com/xiexinbei0318/p/11427006.html