-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCycleDetectionLL.cpp
65 lines (59 loc) · 1.34 KB
/
CycleDetectionLL.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Brute Force
// TC O(N*N) SC O(1)
bool detectCycle(Node *head)
{
int numberOfNodesPassed = 0;
Node* outerLoopNode = head;
while(outerLoopNode!=NULL)
{
numberOfNodesPassed++;
outerLoopNode=outerLoopNode->next;
Node* innerLoopNode = head;
int countInnerLoop = numberOfNodesPassed;
while(countInnerLoop--)
{
if(outerLoopNode==innerLoopNode)
return true;
innerLoopNode=innerLoopNode->next;
}
}
}
// Optimized using hashset
// TC O(N) SC O(N)
#include<unordered_set>
bool detectCycle(Node *head)
{
// Write your code here
unordered_set<Node*> st;
while(head!=NULL){
// We reached some earlier node again thus we found a cycle
if(st.find(head)!=st.end())
return true;
// Add the node to the hashset of already seen nodes
st.insert(head);
head = head->next;
}
// we did'nt found any cycle
return false;
}
// More Optmized
// TC O(N) SC O(1)
bool detectCycle(Node *head)
{
if(head ==NULL || head->next ==NULL)
return false;
// Slow Pointer - This will be incremented by 1 Nodes.
Node* slow = head;
// // Fast Pointer - This will be incremented by 2 Nodes.
Node* fast = head->next;
while(slow!=fast)
{
// We reached the end of the List and haven't found any cycle
if(fast ==NULL || fast->next==NULL)
return false;
slow = slow->next;
fast = fast->next->next;
}
// we found a cycle
return true;
}