Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Floyad cycle detection algo #351

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions algorithms/data-structures/linkedlist/FloyadCycleAlgo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}