https://leetcode.com/problems/linked-list-cycle/
思路1:hash map
开一个哈希表,标记访问过的节点,如果重复访问了某一节点,说明有环。需要额外O(n)的空间复杂度。
C++
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;
}
};
思路2:快慢指针
用一快一慢指针,开始两个指针都指向链表头部。慢指针每次向前走一步,快指针每次向前走两步。如果有环,则两个指针最终一定会相遇。这种方法无须额外的空间。
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head) return false;
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};