forked from DHEERAJHARODE/Hacktoberfest2024-Open-source-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetectCycle.cpp
58 lines (44 loc) · 863 Bytes
/
detectCycle.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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
bool detect_Cycle(Node* head)
{
if(head == NULL || head->next == NULL)
return 0;
Node* slow = head;
Node* fast = head;
while(fast->next != NULL && fast->next->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
return false;
}
int main()
{
Node* head;
head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head->next->next->next->next->next = head->next->next;
//display(head);
bool cycle_Present = detect_Cycle(head);
if(cycle_Present)
cout << "Cycle is Present" << endl;
else
cout << "Cycle is not present" << endl;
return 0;
}