Given a linked list, determine if it has a cycle in it.
// Two pointers chasing each other.
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
if(slow == fast) return true;
}
return false;
}
A Cycle means that the address will be visited twice.
bool hasCycle(ListNode *head) {
if(!head) return false;
set<ListNode*> address;
ListNode* slow = head;
while(slow) {
if(address.find(slow) != address.end()) return true;
address.insert(slow);
slow = slow->next;
}
return false;
}