Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
/**
* 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)
{
set<ListNode*> s;
if(head == NULL)
return NULL;
ListNode *p = head;
while(p)
{
if(s.count(p))
{
return p;
}
s.insert(p);
p = p->next;
}
return NULL;
}
};