原题
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.
Follow up:
Can you solve it without using extra space?
分析
跟上题一样,使用额外空间肯定没有问题,但是如果不使用额外空间呢?之前想到用两个指针追击,不过只能判断是否有环,因为你也不知道什么时候被追到。
代码
使用额外空间存储指针,返回第一次出现重复访问的指针。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> visit;
ListNode * p = head;
while(p&&p->next)
{
if(visit.find(p)==visit.end())
{
visit.insert(p);
p=p->next;
}
else
{
return p;
}
}
return NULL;
}
};