题目
题目描述
判断给定的链表中是否有环。如果有环则返回true,否则返回false。
你能给出空间复杂度的解法么?
题解
快慢指针
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==nullptr||head->next==nullptr)return false;
ListNode *slow=head,*fast=head->next;
while(slow!=fast){
if(fast==nullptr||slow==nullptr||fast->next==nullptr)return false;
slow=slow->next;
fast=fast->next->next;
}
return true;
}
};
哈希表
class Solution {
public:
bool hasCycle(ListNode *head) {
set<ListNode*> hash_map;
ListNode *p=head;
while(p!=nullptr){
if(hash_map.count(p)){
return true;
}
hash_map.insert(p);
p=p->next;
}
return false;
}
};