The idea is kind of mathematical, I learned it from the discuss. There are others' blogs have better explanation to it, so I just copy the code here.
/**
* 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)
return NULL;
ListNode *slow=head,*fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
fast=head;
while(fast!=slow)
{
slow=slow->next;
fast=fast->next;
}
return fast;
}
}
return NULL;
}
};