Program to detect loop in a linked list
Wed Oct 02 2024 10:02:40 GMT+0000 (Coordinated Universal Time)
Saved by @Rohan@99
#include <iostream>
using namespace std;
class Node
{
public:
int data; // Data stored in the node
Node* next; // Pointer to the next node in the list
};
// Function to detect a loop in a linked list
bool detectCycle(Node* head)
{
Node* slow = head;
Node* fast = head;
while(fast != nullptr && fast->next != nullptr)
{
if(fast == nullptr)
return false;
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
}
int main()
{
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
Node* fourth = new Node();
Node* fifth = new Node();
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = fourth;
fourth->data = 4;
fourth->next = fifth;
fifth->data = 5;
fifth->next = third;
if (detectCycle(head))
{
cout << "Loop detected in the linked list." << endl;
}
else
{
cout << "No loop detected in the linked list." << endl;
}
delete head;
delete second;
delete third;
delete fourth;
delete fifth;
//--------------------------New input set------------------------//
/*Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = nullptr;
if (detectCycle(head))
{
cout << "Loop detected in the linked list." << endl;
}
else
{
cout << "No loop detected in the linked list." << endl;
}
delete head;
delete second;
delete third;*/
//--------------------------New input set------------------------//
/*Node* head = new Node();
head->data = 1;
head->next = head;
if (detectCycle(head))
{
cout << "Loop detected in the linked list." << endl;
}
else
{
cout << "No loop detected in the linked list." << endl;
}
delete head;*/
return 0;
}



Comments