-
Notifications
You must be signed in to change notification settings - Fork 337
/
Copy pathFloyadCycleAlgo.cpp
83 lines (76 loc) · 1.29 KB
/
FloyadCycleAlgo.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *next;
node(int val)
{
data = val;
next = nullptr;
}
};
node *create(node *&root)
{
int x;
cout << "Enter the data : ";
cin >> x;
node *n = new node(x);
if (root == nullptr)
{
n = root;
return root;
}
auto temp = root;
while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = n;
return root;
}
bool checkForLoop(node *&root)
{
auto fast = root;
auto slow = root;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
void display(node *root)
{
cout << endl;
while (root != nullptr)
{
cout << root->data << " -> ";
root = root->next;
}
}
int main()
{
int n;
cout << "enter the number of nodes you want to insert in linked list : ";
cin >> n;
cout << endl;
node *root = new node(0);
for (int i = 0; i < n; i++)
{
create(root);
}
display(root);
if (checkForLoop(root))
{
cout << "\n loop is present !!";
}
else
{
cout << "\n loop is not present !!";
}
return 0;
}