struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode *fast = pHead, *slow = pHead;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
break; //表示可能有环
}
}
//如果走到了NULL 那表示肯定没有环
if(!fast || !fast->next){
return nullptr;
}
//不然的话,把fast和slow中任意一个结点重置为pHead
slow = pHead;
while(slow != fast){
slow = slow -> next;
fast = fast -> next;
}
return fast;
}
};