#include <iostream>
#include <unordered_set>
using namespace std;
// Data Structure to store a linked list node
struct Node
{
int dt;
Node* next;
};
// Helper function to create a new node with the given data and
// pushes it onto the front of the list
void push(Node*& headRef, int dt)
{
// create a new linked list node from heap
Node* newNode = new Node;
newNode->dt = dt;
newNode->next = headRef;
headRef = newNode;
}
// Function to detect Cycle in a linked list using Hashing
bool detectcyc(Node *head)
{
Node *current = head;
unordered_set<Node*> set;
// traverse the list
while (current)
{
// return false if we already have seen this node before
if (set.find(current) != set.end())
return true;
// insert current node into the set
set.insert(current);
// move to the next node
current = current->next;
}
// we reach here if list does not contain any cycle
return false;
}
// Detect Cycle in a linked list
int main()
{
// input keys
int k[] = { 1, 2, 3, 4, 5 };
int n = sizeof(k) / sizeof(k[0]);
Node* head = nullptr;
for (int i = n - 1; i >= 0; i--)
push(head, k[i]);
// insert cycle
head->next->next->next->next->next = head->next->next;
if (detectcyc(head))
cout << "Cycle Found";
else
cout << "No Cycle Found";
return 0;
}
Method 2 – Floyd’s Cycle Detection Algorithm