Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路1:hash map
开一个哈希表,标记访问过的节点,如果重复访问了某一节点,说明有环。需要额外O(n)的空间复杂度。
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:快慢指针
用一快一慢指针,开始两个指针都指向链表头部。慢指针每次向前走一步,快指针每次向前走两步。如果有环,则两个指针最终一定会相遇。这种方法无须额外的空间。
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode p = head;
ListNode q = head;
if(head == null){
return false;
}
while(p != null && p.next != null){
p = p.next.next;
q = q.next;
if(p == q){
return true;
}
}
return false;
}
}