原题链接:141. 环形链表
solution: 利用图存储已经遍历过的结点
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode *> map; //存储已经遍历的结点
ListNode *cur = head;
while(cur != nullptr){
if(map.count(cur)) return true;
map.insert(cur);
cur = cur->next;
}
return false;
}
};
利用快慢指针,快指针一次走2步,满指针一次走1步,他们一定会在环中相遇
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
while(fast != nullptr && fast->next != nullptr){
fast = fast->next->next;
slow = slow->next;
if(fast == slow) return true;
}
return false;
}
};