Wednesday, 19 October 2016

Floyd's Cycle Detection

/*
Tanzila Islam
Southeast University
mail : tanzilamohita@gmail.com
*/ 

 

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

// Floyd's Cycle Detection

struct Node{
    int data;
    struct Node *next;
};

//check if there is a cycle or not
bool has_cycle(Node* frontPoint)
{
    //if frontPoint is null
    if(frontPoint==NULL) return 0;
    //initialize hare & tortoise at frontPoint
    Node *tortoise=frontPoint, *hare=frontPoint;
    //if current hare position & next hare position is NULL
    while(hare!=NULL && hare->next!=NULL)
    {
        // tortoise runs one step
        tortoise=tortoise->next;
        // hare runs two step
        hare=hare->next->next;
        //if tortoise & hare meets at same point
        if(tortoise==hare) return 1;
    }
    return 0;
}

int main(){

    Node *current = new Node();
    Node *frontPoint = current;
    current->data = 1;

    Node *tmp = new Node();
    tmp->data = 2;
    current->next=tmp;
    current=current->next;

    Node *tmp2 = new Node();
    tmp2->data = 3;
    current->next=tmp2;
    current=current->next;

    current->next=tmp; // cycle here. comment to remove cycle

    cout<<has_cycle(frontPoint);
}

No comments:

Post a Comment