一、学习要点:
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;
}
};