牛客討論區的做法,perfect
/*
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 || pHead->next->next == NULL)return NULL;
ListNode* slow = pHead->next;
ListNode* quick = pHead->next->next;
while(slow != quick) {
if(quick->next != NULL && quick->next->next != NULL) {
quick = quick->next->next;
slow = slow->next;
}
else return NULL;
}
ListNode* p = pHead;
while(p != quick) {
p = p->next;
quick = quick->next;
}
return p;
}
};