From 890c1fdc43c94a8ebdc5903eb814ba9b2c7458d0 Mon Sep 17 00:00:00 2001 From: Kriti1262 <100215152+Kriti1262@users.noreply.github.com> Date: Mon, 10 Oct 2022 23:45:04 +0530 Subject: [PATCH] Create DetectLoop.cpp --- DetectLoop.cpp | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 DetectLoop.cpp diff --git a/DetectLoop.cpp b/DetectLoop.cpp new file mode 100644 index 0000000..3992ed2 --- /dev/null +++ b/DetectLoop.cpp @@ -0,0 +1,70 @@ +// C++ program to detect loop in a linked list +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; +}; + +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; + + /* 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) +{ + unordered_set s; + while (h != NULL) { + // If this node is already present + // in hashmap it means there is a cycle + // (Because you will be encountering the + // node for the second time). + if (s.find(h) != s.end()) + return true; + + // If we are seeing the node for + // the first time, insert it in hash + s.insert(h); + + 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; +} +