哈希方式
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_map<ListNode *, bool> m;
while(head){
if(m.find(head) != m.end())
return true;
m[head] = true;
head = head->next;
}
return false;
}
};快慢指针
class Solution {
public:
bool hasCycle(ListNode *head) {
//快慢指针
if(!head) return false;
ListNode * slow = head;
ListNode * fast = head->next;
while(slow != fast && slow && fast){
slow = slow->next;
fast = fast->next;
if(!fast) return false;
fast = fast->next;
}
if(slow == fast)
return true;
return false;
}
};
京公网安备 11010502036488号