find whether there is a loop in a linked list. Do you have other ways
instead of using a quick pointer and a slow pointer?
find whether there is a loop in a linked list. Do you have other
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are a variety of ways you can do this, depending on your situation.
Add each node to a Set of some kind when you reach it. Go through the list until you reach the end or find a node already in the Set.
If you have spare space in the nodes, you can mark each node as “visited” or not and walk the list until you find one you’ve already marked.
These, of course, all have downsides (like high memory use) or situations where they’re not usable, while the two-pointer method doesn’t use extra memory and is applicable pretty much everywhere.