Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

changes done #166

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
69 changes: 69 additions & 0 deletions loopdetection.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// C++ program to detect loop in a linked list
#include <bits/stdc++.h>
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<Node*> 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;
}