tags:

views:

238

answers:

2

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?

+1  A: 

You will have to mark each node as visited and detected an already visited node that has your mark. Problem is what to mark it with so you don't have to run the list to reset everything before or after.

No Refunds No Returns
+2  A: 

There are a variety of ways you can do this, depending on your situation.

  1. 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.

  2. 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.

Anon.