题目描述
思路:常见的方法,双指针追击问题,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