Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
class Solution {
public:
/*algorithm: hash solution
time O(n) space O(n)
*/
bool hasCycle(ListNode *head) {
unordered_set<ListNode*>S;
ListNode* p = head;
while(p){
if(S.count(p))return true;
S.insert(p);
p = p->next;
}
return false;
}
};
class Solution {
public:
/*algorithm: runner solution
time O(n) space O(1)
*/
bool hasCycle(ListNode *head) {
ListNode* faster = head,*slower = head;
while(faster&&faster->next){
slower = slower->next;
faster = faster->next->next;
if(faster == slower)return true;
}
return false;
}
};