From bb741023cffd0a3407c1ec6bc4c0b54adbb845af Mon Sep 17 00:00:00 2001 From: Nupur Hardiya <113535580+NupurHardiya@users.noreply.github.com> Date: Wed, 19 Oct 2022 14:54:41 +0530 Subject: [PATCH] Create detectloop.cpp --- detectloop.cpp | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 detectloop.cpp diff --git a/detectloop.cpp b/detectloop.cpp new file mode 100644 index 0000000..a411ea9 --- /dev/null +++ b/detectloop.cpp @@ -0,0 +1,72 @@ +// C++ program to detect loop in a linked list +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; + int flag; +}; + +void push(struct Node** head_ref, int new_data) +{ + /* allocate node */ + struct Node* new_node = new Node; + + /* put in the data */ + new_node->data = new_data; + + new_node->flag = 0; + + /* link the old list off the new node */ + new_node->next = (*head_ref); + + /* move the head to point to the new node */ + (*head_ref) = new_node; +} + +// Returns true if there is a loop in linked list +// else returns false. +bool detectLoop(struct Node* h) +{ + while (h != NULL) { + // If this node is already traverse + // it means there is a cycle + // (Because you we encountering the + // node for the second time). + if (h->flag == 1) + return true; + + // If we are seeing the node for + // the first time, mark its flag as 1 + h->flag = 1; + + h = h->next; + } + + return false; +} + +/* Driver program to test above function*/ +int main() +{ + /* Start with the empty list */ + struct Node* head = NULL; + + push(&head, 20); + push(&head, 4); + push(&head, 15); + push(&head, 10); + + /* Create a loop for testing */ + head->next->next->next->next = head; + + if (detectLoop(head)) + cout << "Loop found"; + else + cout << "No Loop"; + + return 0; +} +// This code is contributed by Geetanjali