Try the Hare and Tortoise approach. Basically have 2 ptrs both
pointing to the start of thelist. Increment one pointer by 1 and
another by 2. After each increment comapre if they are equal. If
there is a loop the pointers would meet.
let me see if I understand this.
so if I have alist
1 1 3
That's not a loop. That's a repeated element,
not a repeated node.
A loop in a singly linked list is necessarily
an infinite loop.
I guess you meant something like
for(p1 = start; p1 != end; ++p1)
{
p2 = p1;
++p2
for(; p2 != end; ++p2)
if(p1 == p2)
! there is a loop !
}
No, the classic technique is this:
p1=start;
p2=start;
while(p1!=NULL && p2!=NULL) {
if (p1==p2)
return "there is a (infinite) loop";
p1=p1+1;
p2=p2+2;
}
return "there is no loop";
If the linked list has no loop, then it is
doing a traversal all the way to the end,
which is O(n), and no worse than doing a element lookup.
If the linked list has a loop, then p1 and p2
will eventually meet (since no matter where the
loop starts, the length before the loop,
and the length inside the loop is always either odd,
or even. And so either p1 and p2 meet during the first
pass thru the loop, or during the second loop.
So it is O(2n), which is O(n) also.
- JT