题目描述
样例
C++ 代码
/**
* 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) {
if (!head || !head->next) return NULL;
auto s = head, f = head;
while (f) {
s = s->next, f = f->next;
if (!f) return NULL;
f = f->next;
if (s == f) {//遇到后两个点同时从D点出发 然后遇到的第一个点就是环的起点
s = head, f = f;
while (s != f) s = s->next, f = f->next;
return s;
}
}
return NULL;
}
};