Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. // Given a circular linked list, implement an algorithm which returns node at
  2. // the beginning of the loop.
  3. // DEFINITION
  4. // Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an
  5. // earlier node, so as to make a loop in the linked list.
  6. // EXAMPLE
  7. // input: A -> B -> C -> D -> E -> C [the same C as earlier]
  8. // output: C
  9.  
  10. #include <list>
  11. #include <cassert>
  12. #include <set>
  13.  
  14. int FirstNodeInCycle(std::list<int> list) {
  15.   std::set<int> visited;
  16.   for (auto it = list.begin(); it != list.end(); ++it) {
  17.     if (visited.find(*it) != visited.end()) {
  18.       return *it;
  19.     }
  20.     visited.insert(*it);
  21.   }
  22.   return -1;
  23. }
  24.  
  25. int main(int argc, char* argv[]) {
  26.   assert(FirstNodeInCycle(std::list<int>({1,2,3,4,5,6,3,7})) == 3);
  27.   assert(FirstNodeInCycle(std::list<int>({})) == -1);
  28.   assert(FirstNodeInCycle(std::list<int>({1, 2, 3})) == -1);
  29.   return 0;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement