一、學習要點:
1.快慢指針法,存在鏈表環的話,兩指針肯定會相遇;
2.入口位置由兩快慢指針相遇時,改變慢指針指向表頭,和慢指針等速前進,再次相遇的地點決定;
3.講的比較好的一個博客:https://blog.csdn.net/willduan1/article/details/50938210
二、代碼:
struct ListNode
{
int val;
ListNode* next;
ListNode(int x):val(x),next(NULL){}
};
class Solution{
public:
ListNode* detectcycle(ListNode *head)
{
ListNode* fast=head;
ListNode *slow=head;
bool iscycle=false;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
if(slow==fast)
{
slow=head;
while(slow!=head)
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
}
return NULL;
}
};