Created
January 25, 2014 00:54
-
-
Save tolinwei/8610026 to your computer and use it in GitHub Desktop.
This file contains 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
#include <iostream> | |
//#include <string> | |
using namespace std; | |
class Node | |
{ | |
public: | |
char value; | |
Node *next; | |
Node(int v) : value(v) {} | |
}; | |
char find_loop(Node *head) | |
{ | |
Node *slow = head; | |
Node *fast = head; | |
//------------------------------ | |
slow = slow->next; | |
if (fast->next != NULL) { | |
fast = fast->next->next; | |
} | |
//------------------------------ | |
//cout << (slow == fast) << endl; | |
while (fast->next != NULL && slow != NULL && fast != slow) { | |
//cout << "y" << endl; | |
slow = slow->next; | |
fast = fast->next->next; | |
} | |
if (slow != fast) { | |
return '|'; | |
} | |
//cout << slow->value << endl; | |
//restart | |
slow = head; | |
while (slow != fast) { | |
slow = slow->next; | |
fast = fast->next; | |
} | |
return slow->value; | |
} | |
int main() | |
{ | |
/* 'd' is the start of loop */ | |
Node *a = new Node('a'); | |
Node *b = new Node('b'); | |
Node *c = new Node('c'); | |
Node *d = new Node('d'); | |
Node *e = new Node('e'); | |
Node *f = new Node('f'); | |
Node *g = new Node('g'); | |
Node *h = new Node('h'); | |
Node *i = new Node('i'); | |
Node *j = new Node('j'); | |
Node *k = new Node('k'); | |
a->next = b; | |
b->next = c; | |
c->next = d; | |
d->next = e; | |
e->next = f; | |
f->next = g; | |
g->next = h; | |
h->next = i; | |
i->next = j; | |
j->next = k; | |
k->next = d; | |
cout << find_loop(a) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment