题目
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
if(pHead==NULL)return NULL;
//找到环
ListNode* pfast = pHead->next, *pslow = pHead;
while(pfast!=NULL && pslow!=NULL && pslow!=pfast){
pfast = pfast->next;
pslow = pslow->next;
if(pfast!=NULL)
pfast = pfast->next;
}
//计算环的元素个数
int count = 1;
ListNode* temp = pfast->next;
if(pfast==pslow&&pfast!=NULL){
while(temp!=pfast){
temp = temp->next;
count++;
}
}
else
return NULL;
//找入口
ListNode* phead1=pHead,*phead2=pHead;
for(int i=0;i<count;i++)
phead1 = phead1->next;
while(phead1!=phead2)
{
phead1 = phead1->next;
phead2 = phead2->next;
}
return phead1;
}
};