algorithm - How to determine if a linked list has a cycle using only two memory locations -


Does anyone know the algorithm to find that only two variables are used to get into the linked list? By saying that you have a linked list of objects, no matter what type of object is there, I have an indicator for the head of the linked list in a variable and only one variable is given to me That's where my list entered Can go

So to compare my plan indicator values ​​is to see if there is only one sign. The list is of a finite size but can be very large, I can set both the variables on the head and then cross the list with the second variable, always check that it is equal to the other variable, but if I hit a loop so I will never take it. I am thinking that the list should be done with different rates for comparison of travel and pointer value. Any ideas?

I recommend using the flow-cycl-tracking algorithm aka Turtle and green algorithm . It has the complexity of O (N) and I think it meets your needs.

Example code:

  Function Boolean hello (node ​​startNode) {node slow node = node fast node 1 = node fastNode2 = startNode; While (slow node & fastdownload 1 = fastdownload 2.x) & amp; Foundnode 2 = fastdownd 1. Anttext ()) {If (slow node == fastdownd 1 || slow node == Fast note 2) is true; SlowNode = slowNode.next (); }   return false; }  

More information on Wikipedia.


Comments