Here is the problem, it is from Sedgwick\'s excellent Algorithms in Java (q 3.54)
Given a link to a node in a singly linked list that contains no null links (i.e. ea
Check out this: Puzzle: Loop in a Linked List
Pointer Marking: In practice, linked lists are implemented using C structs with at least a pointer; such a struct in C shall be 4-byte aligned. So the least significant two bits are zeros. While traversing the list, you may ‘mark’ a pointer as traversed by flipping the least significant bit. A second traversal is for clearing these bits.
just remenber where have you been and if you came at same node it is over.
Try storing entries in binary tree and you have O(N*log(N)) time and O(N) space comlexity
EDIT
You can use Log(N) space comlexity if you do not store every but in exponetial order link. That mean that you store 1st, 2nd, 4th, 8th, 16th and then if you get hit you have to continue from that point. Time comlexity for this one is N*Log(n)^2
The most elegant solution is Floyd's cycle-finding algorithm: http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare
It runs in O(N) time, and only constant amount of memory is required.
The tortoise and hare algorithm can give you both the cycle length and the number of nodes before the cycle begins (λ and μ respectively).