题目描述
一个链表中包含环,请找出该链表的环的入口结点。
弗洛伊德判环,注意没有环的情况。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
if(pHead==NULL||pHead->next==NULL)
return NULL;
if(pHead->next==pHead)
return pHead;
ListNode* fast=pHead;
ListNode* slow=pHead;
while(fast!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
break;
}
if(fast==NULL)
return NULL;
fast=pHead;
while(fast!=slow)
{
fast=fast->next;
slow=slow->next;
}
return fast;
}
};