Simple huh...
Cycle in Linked List
The best way to solve this is have 2 points traverse the list. One of them is incremented by 1 and the other is incremented by 2. Traverse the list until they pointers point at the same item or one of them reaches the end of the list. Proof of this is left as an exercise to the reader :-)
It is amazing how many questions pop up around exam time ;-)
Six
I incorectly assumed he was looking for the WHOLE list accidentally circling back...i see that was way to simple. But you are assuming that a cycle will always be directly onto itself. What about a->b b->c c->a, etc. So REALLY ... to detect the GENERAL case where ANY form of cycling occurs, the only possible algorithm is to do the equivelent of marking each node you visit as VISITED...either by setting some value of it, or storing a pointer to it in another list. This is a VERY inefficient thing to do (grows in size by n, and in speed by n^2), but it is the ONLY general case algorthim. Oh well..
Counter ptr1 ptr2
0 a a
1 b c
2 c b
3 a a
So after a few iterations we find that there is a cycle in the list. I've proven this myself rigorously and it works in the general case.
If you want to find _where_ the cycle occurs (which might have been what the original poster wanted...), then you'll have to use a method similar to Xia's.
Using the increment pointer twice method works as described but I caution you to be sure to check the validity of the pointer beyond the current node before you dereference it. I always found that dereferencing ptr->next->next was dangerous because you don't know if ptr->next is null unless you test it. If your on node ptr then you know that by its constructor ptr->next is valid though you can't assume ptr->next->next is the same.
Kressilac.
a->b
b->c
c->b
now when you try the one-two pointers.
Counter ptr1 ptr2 0 a a 1 b c 2 c b 3 b c 4 c b 5 b c
Like I say, I've seen this algo before, so what am I doing wrong here?