diff --git "a/cpp/Floyd\342\200\231s Cycle Finding Algorithm" "b/cpp/Floyd\342\200\231s Cycle Finding Algorithm" new file mode 100644 index 00000000..bd53d332 --- /dev/null +++ "b/cpp/Floyd\342\200\231s Cycle Finding Algorithm" @@ -0,0 +1,73 @@ +#include +using namespace std; + +class Node { +public: + int data; + Node* next; + + Node(int data) + { + this->data = data; + next = NULL; + } +}; + +Node* head = NULL; +class Linkedlist { +public: + void insert(int value) + { + Node* newNode = new Node(value); + if (head == NULL) + head = newNode; + else { + newNode->next = head; + head = newNode; + } + } + + 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(11); + l1.insert(22); + l1.insert(33); + l1.insert(44); + l1.insert(55); + + Node* temp = head; + while (temp->next != NULL) + temp = temp->next; + + temp->next = head; + + + if (l1.detectLoop()) + cout << "Loop exists in the" + << " Linked List" << endl; + else + cout << "Loop does not exists " + << "in the Linked List" << endl; + + return 0; +}