文章目录
- 1.题目
- 2.代码
1.题目
- 题目要求
- 思路:
(1)用一个哈希表unordered_map<ListNode*,bool> visited,记录每个元素是否被访问过,一旦出现某个元素被重复访问,说明有环,空间复杂度O(n),时间复杂度O(N)
(2)这道题是快慢指针的经典应用。只需要设两个指针,一个每次走一步的慢指针和一个每次走两步的快指针,如果链表里有环的话,两个指针最终肯定会相遇。
时间复杂度是O(n),空间复杂度O(1);
2.代码
class Solution{
public:
bool hasCycle(ListNode* head)
{
ListNode* slow=head,fast=head;
while (fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
if (slow==fast) return true;
}
return false;
}
};
使用哈希表
class Solution{
public:
bool hasCycle(ListNode* head)
{
if (!head || !head->next) return false;
unordered_map<ListNode*/*address*/,int/*occurances*/> m;
ListNode* pre=head;
while(pre)
{
if (m[pre] > 0)
return true;
else
m[pre]++;
pre=pre->next;
}
return false;
}