題目描述
思路:常見的方法,雙指針追擊問題,pFast指針每次走兩步,pSlow指針每次走一步,如果pFast能夠與pSlow指針相遇,則一定有環。
關於證明:參考
/*
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)
return NULL;
ListNode* pSlow=pHead;
ListNode* pFast=pHead;
// detect if the linklist is a circle
while(pFast!=NULL && pFast->next!=NULL){
pSlow=pSlow->next;
pFast=pFast->next->next;
if(pSlow==pFast)
break;
}
// if it is a circle
if(pFast!=NULL){
pSlow=pHead;
while(pSlow!=pFast){
pSlow=pSlow->next;;
pFast=pFast->next;
}
}
return pFast;
}
};
LeetCode題目:142. Linked List Cycle II