简体   繁体   中英

Detecting loop in Linked List

I saw this question on the Related section and after going through some of the discussions, i see that the most common solution is the hare and tortoise algorithm. but another suggested solution that i saw (which is what i would have done) is to include the a third instance variable of a Node class that would keep track of nodes it has visited, like a boolean variable. so is this considered a valid solution?

Your solution is definitely a valid one, in the sense that it will get the job done.

However, the problem of detecting a loop is usually formulated with the additional constraint of using O(1) additional memory. The hare and tortoise algorithm satisfies this constraint, while your algorithm does not: it requires O(N) additional memory to store the per-node booleans.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM