Skip to content

Added the code for Detection of Floyd's Cycle in c++ with comments for understanding. #218

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
79 changes: 79 additions & 0 deletions Adding-Floyd-cycle-detection-algorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*Floyd’s cycle finding algorithm or Hare-Tortoise algorithm is a pointer algorithm that uses only two pointers, moving through the sequence at different speeds. This algorithm is used to find a loop in a linked list. It uses two pointers one moving twice as fast as the other one. The faster one is called the fast pointer and the other one is called the slow pointer.*/

//***** Code for Detection of Floyd's Cycle in C++ *****

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
int data;
Node* next;

Node(int data)
{
this->data = data;
next = NULL;
}
};

// initialize a new head for the linked list
Node* head = NULL;
class Linkedlist {
public:
// insert new value at the start
void insert(int value)
{
Node* newNode = new Node(value);
if (head == NULL)
head = newNode;
else {
newNode->next = head;
head = newNode;
}
}

// detect if there is a loop in the linked list
bool detectLoop()
{
Node *slowPointer = head,
*fastPointer = head;

while (slowPointer != NULL
&& fastPointer != NULL
&& fastPointer->next != NULL) {
slowPointer = slowPointer->next;
fastPointer = fastPointer->next->next;
if (slowPointer == fastPointer)
return 1;
}

return 0;
}
};

int main()
{
Linkedlist l1;
// inserting new values
l1.insert(10);
l1.insert(20);
l1.insert(30);
l1.insert(40);
l1.insert(50);

// adding a loop for the sake of this example
Node* temp = head;
while (temp->next != NULL)
temp = temp->next;

temp->next = head;

// loop added;

if (l1.detectLoop())
cout << "Loop exists in the Linked List\n"<<endl;
else
cout << "Loop does not exists in the Linked List\n"<<endl;
return 0;
}
Binary file added Adding-Floyd-cycle-detection-algorithm.exe
Binary file not shown.