Amazon Interview Question

Given a linked list containing integers as values, write an algorithm that detects if there is a loop or cycle in the list.

Interview Answers

Anonymous

Aug 24, 2012

Another way is to look at the pointer references. Basically, if you store a temporary list of visited nodes you'll have references to each one. Now the value they store may not be unique, but the memory address will be (it should be a new object). So if you encounter a duplicate reference/memory location you've got a loop since you've got two references to the same node (the original node and the looping pointer to it).

1

Anonymous

Jul 29, 2012

I wasn't prepared enough and got this wrong, but apparently one solution involves creating two iterators, one slow and one fast, and seeing if the fast one "laps" the slow one. If they are never in the same place, there's no cycle.