点击打开链接
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 && slow!=NULL && fast->next!=NULL) {
slow = slow->next;
fast = fast->next->next;
if(fast==slow) break;
}
if(fast==NULL || fast->next ==NULL) return NULL;
slow =head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return fast;
}
};
int main()
{
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/b696446cc59f2ea5f12d863e6563a06b.png)