Created
January 27, 2011 01:47
-
-
Save jsundram/797906 to your computer and use it in GitHub Desktop.
detect loop (I've seen this one before)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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