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

Create detect_loop.cpp #4735

Open
wants to merge 1 commit into
base: master
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
59 changes: 59 additions & 0 deletions detect_loop.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// C++ program to detect loop in a linked list
// using hashset
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
int data;
Node* next;
Node(int x) {
this->data = x;
this->next = nullptr;
}
};

// Function that returns true if there is a loop in linked
// list else returns false.
bool detectLoop(Node* head) {
unordered_set<Node*>st;

// loop that runs till the head is nullptr
while (head != nullptr) {

// 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 (st.find(head) != st.end())
return true;

// If we are seeing the node for
// the first time, insert it in hash
st.insert(head);

head = head->next;
}
return false;
}

int main() {

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40 -> 50 -> 60
Node* head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
head->next->next->next = new Node(40);
head->next->next->next->next = new Node(50);
head->next->next->next->next->next = new Node(60);

head->next->next->next->next = head;

if (detectLoop(head))
cout << "true";
else
cout << "false";

return 0;
}