Skip to content

Instantly share code, notes, and snippets.

@jsundram
Created January 27, 2011 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsundram/797906 to your computer and use it in GitHub Desktop.
Save jsundram/797906 to your computer and use it in GitHub Desktop.
detect loop (I've seen this one before)
class Node
{
public:
Node() : next(NULL), value(0) {}
Node(int v) : next(NULL), value(v){}
Node* next;
int value;
};
bool detect_loop(Node* head)
{
Node *n1, *n2;
n1 = n2 = head;
while (n1->next != NULL && n2->next != NULL)
{
n1 = n1->next;
n2 = n2->next;
if (n2->next != NULL)
n2 = n2->next;
if (n1 == n2) return true;
}
return false;
}
int main()
{
// Make a list with a loop in it.
int n = 10;
Node* head = new Node(0);
Node* curr = head;
for (int i = 1; i < n; i++)
{
Node* t = new Node(i);
curr->next = t;
curr = t;
}
// LOOP! (comment out to make regular)
curr->next = head;
bool loop = detect_loop(head);
std::cout << "There is a loop: " << loop << std::endl;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment