-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDetectACycleInLinkedList.cpp
More file actions
44 lines (40 loc) · 895 Bytes
/
Copy pathDetectACycleInLinkedList.cpp
File metadata and controls
44 lines (40 loc) · 895 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Q32 https://leetcode.com/problems/linked-list-cycle/
// Slow fast approach
//Time: O(n)
//Space: O(1)
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head || !head->next) return false;
ListNode *s=head;
ListNode *f=head;
while(f->next&&f->next->next){
s=s->next;
f=f->next->next;
if(s==f)
return true;
}
return false;
}
};
//Hashmap approach
//Time: O(n)
//Space: O(n)
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head || !head->next) return false;
unordered_map<ListNode*,int> m;
ListNode *t=head;
bool res=false;
while(t->next){
m[t]++;
if(m[t]>1){
res=true;
break;
}
t=t->next;
}
return res;
}
};