I'm trying to find a circle in a linked list, and return the node at the beginning of the circle. For example, if the list was A -> B -> C -> D -> C -- we would return C
Here is my code:
ListNode<T> * findCircle()
{
  map<ListNode<T>*, bool> addresses;
  ListNode<T>* node = head;
  if(addresses.find(node)->second)
    cout << " wtf " << endl;
  while(node)
  { 
    if((addresses.find(node))->second)
    {
      return node;
    } 
    else
      addresses.insert(pair<ListNode<T>*,bool>(node, 1));
    node = node->next;
  }
  return NULL;
}
I have a few questions:
1) is this the right way to approach the problem
2) am I using the most efficient ways to lookup/insert the keys and values into the table
3) why is it not working? When I check in the map for head, before I've inserted head, it still executes that if statement and prints "wtf". My algorithm is to insert the node as a key with a true value if it is not found in the map, otherwise return the node if the key is already in the map.
I tried doing this with std::set but it gave me trouble, so I switched to map. What baffles me is that the following code works (Code to remove duplicates in a linked list, using a lookup table) using exactly the same methodology.
  void removeDuplicates()
    {
      map<T, bool> listData;
      ListNode<T> *node;
      ListNode<T> *prev = node;
      for(node = head; node; node = node->next)
      {
        if(listData.find(node->data)->second)
        {
          prev->next = node->next;
          delete node;
        }
        else
        {
          listData.insert( pair<T, bool>(node->data, 1));
        }
        prev = node;
      }
    }
Is it just a fluke that the second block of code does what it is supposed to, but the first does not?
 
     
    