c++ - Floyd's cycle-finding algorithm -


i'm trying find algorithm on c++ in .net can't, found one:

// best solution function boolean hasloop(node startnode){   node slownode = node fastnode1 = node fastnode2 = startnode;   while (slownode && fastnode1 = fastnode2.next() && fastnode2 = fastnode1.next()){     if (slownode == fastnode1 || slownode == fastnode2) return true;     slownode = slownode.next();   }   return false; } 

but doesn't seem right, or wrong? how can prove hare meet tortoise @ end? in advance explanation how work , proof

edited

about solution, found in regular algorithm use 1 fast iterator here use two, why?

the idea in code you've found seems fine. 2 fast iterators used convenience (although i'm positive such kind of 'convenience', putting lot of 'action' in condition of while loop, should avoided). can rewrite in more readable way 1 variable:

while (fastnode && fastnode.next()) {     if (fastnode.next() == slownode || fastnode.next().next() == slownode) {         return true;     }     fastnode = fastnode.next().next();     slownode = slownode.next(); } 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -