This is an interview question that I heard several times. Although I never tried to implement any kind of loop detection, the answer that most interviewers seem to like is to repeat the list and store the visited nodes in a hash table. If you encounter a conflict while storing in a table, you have a loop in your list.
Edit: in an attempt to suggest some code for an example, this is what I will probably try to do (assuming you have some kind of LinkedList<EntityNode> object). I updated this to use a HashSet instead of a HashMap, so it was simpler (as PM 77-1 pointed out).
public bool detectLoop(LinkedList<EntityNode> list) { Set<EntityNode> nodeSet = new HashSet<EntityNode>(); EntityNode curNode = list.getHead(); boolean loopDetected = false; if(curNode != null) { while(curNode.getNextNode() != null && !loopDetected) { cureNode = curNode.getNextNode(); loopDetected = !nodeSet.add(curNode); } } return loopDetected; }
I have not had the opportunity to verify this, but it should work. The reason is that the add() method for HashSet returns true if this set did not already contain the specified element . Therefore, if an EntityNode already exists in the set, it will return false, which means that a loop has been detected.
Since my answer has already been removed, I want to say that there are other solutions. Another that was noted in this thread is the turtle and the hare algorithm. You can find more information about this in this thread or on this wiki page .
source share