思路:找到环的节点数目n,然后设定一快和慢指针,先让快指针走n步,然后和慢指针一起走,当
两个指针相遇的时候的节点就是链表的入口节点
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
if(pHead == nullptr)
return nullptr;
ListNode * publicNode = findPublicNode(pHead);//找到在环中的一个节点
if(publicNode == nullptr)
return nullptr;
int count = 1;
ListNode * pNode1 = publicNode;
while(pNode1->next != publicNode)//统计环中节点数目
{
count++;
pNode1 = pNode1->next;
}
pNode1 = pHead;
for(int i = 0; i < count; i++)//先让快指针走count个节点
pNode1 = pNode1->next;
ListNode * pNode2 = pHead;
while(pNode1 != pNode2)//快指针和慢指针一起走
{
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
return pNode1;
}
ListNode * findPublicNode(ListNode * Head)//找到环中的节点
{
if(Head == nullptr)
return nullptr;
ListNode * pSlow = Head->next;
if(pSlow == nullptr)//只有一个节点当然不会有环了
return nullptr;
ListNode * pFast = pSlow->next;//快指针
while(pSlow != nullptr && pFast != nullptr)
{
if(pSlow == pFast)//相遇的节点就是环中的节点
return pFast;
pSlow = pSlow->next;
pFast = pFast->next->next;
}
return nullptr;
}
};