分三大步:
- 判断是否有环。可以通过设置快慢指针。同时从头结点出发,慢指针走一步,快指针走两步。
- 如果有环,统计环中结点。
- 重新设置两个指针,从头结点开始,一个指针先走 环中结点个数的步数,另一个指针从头开始。二者相遇,即为 环入口:
#include<iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
// ListNode(int x) :
// val(x), next(NULL) {
// }
};
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode* MN = MeetNode(pHead);
if (MN==nullptr)return nullptr;
ListNode* tmp = MN;
int sumnode = 1;
while(tmp->next!=MN)
{
tmp = tmp->next;
sumnode++;
}
tmp = pHead;
for (int i=0;i<sumnode;i++)
{
tmp = tmp->next;
}
ListNode* tmp2 = pHead;
while(tmp!=tmp2)
{
tmp = tmp->next;
tmp2 = tmp2->next;
}
return tmp;
}
ListNode* MeetNode(ListNode* pHead)
{
if (pHead==nullptr)return nullptr;
ListNode* pslow = pHead->next;
if (pslow==nullptr)return nullptr;
ListNode* pfast = pslow->next;
while(pfast!=nullptr && pslow!=nullptr)
{
if (pfast==pslow)
{
return pfast;
}
pslow = pslow->next;
pfast = pfast->next;
if (pfast!=nullptr)
{
pfast = pfast->next;
}
}
return nullptr;
}
};
int main()
{
ListNode list[6];
list[0].val = 1;
list[0].next = &list[1];
list[1].val = 2;
list[1].next = &list[2];
list[2].val = 3;
list[2].next = &list[3];
list[3].val = 4;
list[3].next = &list[4];
list[4].val = 5;
list[4].next = &list[5];
list[5].val = 6;
list[5].next = &list[2];
Solution su;
cout<<su.EntryNodeOfLoop(list)->val<<endl;
return 0;
}