题目描述

一个链表中包含环,请找出该链表的环的入口结点。

/*
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;
}

int LoopLength = lengthOfLoop(pHead);

if (LoopLength == 0){
return NULL;
}

ListNode* faster = pHead;

while (LoopLength--){
faster = faster->next;
}

ListNode* slower = pHead;

while (faster != slower){
faster = faster->next;
slower = slower->next;
}

return faster;
}

private:
int lengthOfLoop(ListNode* pHead){

if (pHead == NULL){
return 0;
}

ListNode* meetNode = NULL;

ListNode* faster = pHead;
ListNode* slower = pHead;

while (faster){
if (faster->next == NULL || faster->next->next == NULL){
return 0;
}

faster = faster->next->next;
slower = slower->next;

if (faster == slower){
meetNode = faster;
break;
}
}

int length = 1;
slower = slower->next;

while (slower != meetNode){
slower = slower->next;
length++;
}

return length;
}

};