代码
方法1 hash表
class Solution {
public:
bool hasCycle(ListNode* head) {
if (head == nullptr || head->next == nullptr) return false;
unordered_map<ListNode*,int> list;
ListNode* cur = head;
while (cur)
{
if (list.find(cur) != list.end()) return true;
list[cur]++;
cur = cur->next;
}
return false;
}
};
方法2 双指针
class Solution {
public:
bool hasCycle(ListNode* head) {
if (head == nullptr || head->next == nullptr) return false;
ListNode *slow = head;
ListNode* fast = head->next;
while (slow!=fast)
{
if (fast == nullptr || fast->next == nullptr) return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};