题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode* slow = pHead;
ListNode* fast = pHead;
int step = 2;
while(fast&&step>0)
{
fast = fast->next;
step--;
}
bool cycle = false;
while(slow&&fast)
{
if(slow == fast)
{
cycle = true;
break;
}
slow = slow->next;
fast = fast->next;
if(fast)
fast = fast->next;
}
if(!cycle)
return NULL;
int lenth=1;
fast = fast->next;
while(fast != slow)
{
lenth++;
fast = fast->next;
}
ListNode* move = pHead;
for(int i = lenth;i>0;i--)
{
move = move->next;
}
while(move != pHead)
{
move = move->next;
pHead = pHead->next;
}
return move;
}
};