Advertisement
jcvitanovic

CTCI, 2.6.

Jan 2nd, 2015
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. /*02.01.2015
  2. CTCI
  3. 2.6 Given a circular linked list, implement an algorithm which returns the node at
  4. the beginning of the loop.
  5. DEFINITION
  6. Circular linked list: A (corrupt) linked list in which a node's next pointer points
  7. to an earlier node, so as to make a loop in the linked list.
  8. EXAMPLE
  9. Input: A - > B - > C - > D - > E - > C [the same C as earlier]
  10. Output: C*/
  11.  
  12. #include<stdio.h>
  13. #include<iostream>
  14.  
  15. using namespace std;
  16.  
  17. class Node{
  18. public:
  19.     Node(int n){
  20.         value = n;
  21.     }
  22.     int value;
  23.     Node *next;
  24. };
  25.  
  26.  
  27. //solution: Floyd's cycle-finding algorithm,"tortoise and the hare algorithm". source: Wikipedia
  28. Node *detectCycle(Node *head){
  29.     Node *fast = head;
  30.     Node *slow = head;
  31.  
  32.     while (1){
  33.         if (!fast->next)
  34.             return NULL; // we've reached the end - no cycle detected
  35.  
  36.         fast = fast->next;
  37.  
  38.         if (!fast->next)
  39.             return NULL; // we've reached the end - no cycle detected
  40.  
  41.         fast = fast->next;
  42.         slow = slow->next; // we moved fast by two, slow by one step
  43.  
  44.         if (fast == slow){
  45.             //meeting point - cycle detected
  46.             break;
  47.         }
  48.     }
  49.     //fast and slow are at the meating point
  50.     //move slow back to begining
  51.     slow = head;
  52.     while (1){
  53.         slow = slow->next;
  54.         fast = fast->next; //move each by one, when they meet again, it is beginning of the cycle
  55.         if (slow == fast){
  56.             return slow; // begining of cycle, return the node!
  57.         }
  58.     }
  59.  
  60.     return NULL;
  61. }
  62.  
  63. int main(){
  64.     Node *one = new Node(1);
  65.     Node *two = new Node(2);
  66.     Node *three = new Node(3);
  67.     Node *four = new Node(4);
  68.     Node *five = new Node(5);
  69.     Node *six = new Node(6);
  70.    
  71.     one->next = two;
  72.     two->next = three;
  73.     three->next = four;
  74.     four->next = five;
  75.     five->next = six;
  76.     six->next = two;
  77.  
  78.     Node *cycleStart = detectCycle(one);
  79.  
  80.     if (cycleStart)
  81.         cout << cycleStart->value << "\n";
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement