题目描述
理解
图片转载于leetcode-知足常乐,题目中出现的一些问题有
slow走过的路程为x+y+m(y+z),fast走过的路程为x+y+n(y+z),理解为取了个特例,得到x=z,然后表示相遇后将slow放置head后同时慢行,再次相遇后就到了环入口。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow=head;
ListNode* fast=head;
while(fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return fast;
}
}
return NULL;
}
};