使用hash表来做
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
//哈希表:每次访问到一个节点,判断该节点是否被访问过
//使用hash表来存储被访问过的节点
unordered_set<ListNode*> seet;
while(head != nullptr)
{
if(seet.count(head))//如果遍历的当前节点统计数量大于0,说明出现过,所以返回true,证明是环
{
return true;
}
seet.insert(head);
head = head->next;
}
return false;
}
};
快慢指针:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
//龟兔赛跑:两个指针同时起步,快指针走两步,慢指针走一步,只要有环,根据相对速度(慢节点不走),一定会相遇
ListNode* slow = head;
ListNode* fast = head;
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if(fast == slow)
{
return true;
}
}
return false;
}
};