Answer by meriton - on strike for How to detect a loop in a linked list?
An alternative solution to the Turtle and Rabbit, not quite as nice, as I temporarily change the list: The idea is to walk the list, and reverse it as you go. Then, when you first reach a node that has...
View ArticleAnswer by TofuBeer for How to detect a loop in a linked list?
I cannot see any way of making this take a fixed amount of time or space, both will increase with the size of the list. I would make use of an IdentityHashMap (given that there is not yet an...
View ArticleAnswer by codaddict for How to detect a loop in a linked list?
You can make use of Floyd's cycle-finding algorithm, also known as tortoise and hare algorithm. The idea is to have two references to the list and move them at different speeds. Move one forward by 1...
View ArticleAnswer by Sparky for How to detect a loop in a linked list?
The following may not be the best method--it is O(n^2). However, it should serve to get the job done (eventually). count_of_elements_so_far = 0; for (each element in linked list) { search for current...
View ArticleAnswer by Larry for How to detect a loop in a linked list?
Tortoise and hare Take a look at Pollard's rho algorithm. It's not quite the same problem, but maybe you'll understand the logic from it, and apply it for linked lists. (if you're lazy, you can just...
View ArticleHow to detect a loop in a linked list?
Say you have a linked list structure in Java. It's made up of Nodes: class Node { Node next; // some user data } and each Node points to the next node, except for the last Node, which has null for...
View ArticleAnswer by Bandish Kumar for How to detect a loop in a linked list?
func checkLoop(_ head: LinkedList) -> Bool { var curr = head var prev = head while curr.next != nil, curr.next!.next != nil { curr = (curr.next?.next)! prev = prev.next! if curr === prev { return...
View ArticleAnswer by RowanStone for How to detect a loop in a linked list?
I'm not sure whether this answer is applicable to Java, however I still think it belongs here:Whenever we are working with pointers on modern architectures we can expect them to be CPU word aligned....
View ArticleAnswer by CausingUnderflowsEverywhere for How to detect a loop in a linked list?
If the linked list structure implements java.util.List. We can use the list size to keep track of our position in the list.We can traverse the nodes comparing our current position to the last node's...
View ArticleAnswer by Ankit kaushik for How to detect a loop in a linked list?
I read through some answers and people have missed one obvious solution to the above problem.If given we can change the structure of the class Node then we can add a boolean flag to know if it has been...
View Article