给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
链表中,用快慢两指针,
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
bool isHaveLoop = false;
ListNode* fast = pHead;
ListNode* slow = pHead;
if(fast == NULL || fast -> next == NULL || fast -> next -> next == NULL){
return NULL;
}
while(fast -> next -> next != NULL){
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow){
isHaveLoop = true;
break;
}
}
if(isHaveLoop){
slow = pHead;
while(slow != fast){
slow = slow -> next;
fast = fast -> next;
}
return slow;
}
return NULL;;
}
};