您的位置:首页 > 其它

LeetCode142—Linked List Cycle II

2016-09-28 21:34 399 查看

原题

原题链接

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;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: