fork(1) download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Node {
  6. public:
  7. Node* next;
  8. int id;
  9. Node(int id, Node* next) : id(id), next(next) {}
  10.  
  11. };
  12.  
  13. Node* FindLoopBegin(Node *head) {
  14. Node *slowptr = head,*fastptr = head;
  15. bool LoopExists = false;
  16. while(slowptr && fastptr){
  17. fastptr = fastptr->next;
  18. //if(fastptr == slowptr) {LoopExists = true;break;}
  19. if(fastptr == NULL) {LoopExists = false; return NULL;}
  20. fastptr = fastptr->next;
  21. slowptr = slowptr->next;
  22. if(fastptr == slowptr) {LoopExists = true;break;}
  23. }
  24. if(LoopExists) {
  25. slowptr = head;
  26. while(slowptr != fastptr){
  27. slowptr = slowptr->next;
  28. fastptr = fastptr->next;
  29. }
  30. return slowptr;
  31. }
  32. return NULL;
  33. }
  34.  
  35. int main()
  36. {
  37. Node* n10 = new Node(10,NULL);
  38. Node* n12 = new Node(12,NULL);
  39. Node* n14 = new Node(14,NULL);
  40. n12->next = n14;
  41. n14->next = n12;
  42. n10->next = n12;
  43. cout<<(FindLoopBegin(n10)->id)<<endl;
  44. return 0;
  45. }
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
12