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; } };
相关文章推荐
- [leetcode] 141& 142 Linked List Cycle I& II
- leetcode-141-142 Linked List Cycle I II
- 关于Linked List Cycle II (leetcode 142) 的几点思考
- LeetCode 142: Linked List Cycle II
- [LeetCode#142]Linked List Cycle II
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- leetcode 142 —— Linked List Cycle II
- leetcode || 142、Linked List Cycle II
- leetcode_142——Linked List Cycle II(set)
- [leetcode]142 Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- [LeetCode 142] Linked List Cycle II
- LeetCode142:Linked List Cycle II
- 【leetcode】【单链表】【142】Linked List Cycle II
- leetcode[142]Linked List Cycle II
- Leetcode#142 Linked List Cycle II
- leetcode 141.Linked List Cycle && 142 .Linked List Cycle ii
- leetcode[141&142]:Linked List Cycle I & II
- LeetCode(141)(142) Linked List Cycle I II
- Java for LeetCode 142 Linked List Cycle II