Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

Added Floyd's Cycle Detect Algorithm #252

Open
wants to merge 1 commit into
base: main
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
46 changes: 46 additions & 0 deletions C++/floyd_cycle_detection_algo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

struct Node{
Node *next;
int val;
Node(int v){
val = v;
next = NULL;
}
};

bool cycleDetect(Node *head){
Node* slow = head;
Node* fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) break;
}

if(fast != slow) return false;
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}

cout<<"The node where cycle starts is "<<slow->val<<"\n";
return true;
}


int main(){
Node* head = new Node(0);
head->next = new Node(1);
head->next->next = new Node(2);
head->next->next->next = new Node(3);
head->next->next->next->next = head->next;
if(!cycleDetect(head)){
cout<<"No cycle detected"<<"\n";
}
return 0;
}