Jul 6, 2009

detect a cycle in linked list

detect a cycle in linked list
bool foo(list* head)
{
if(!head||!head->next) retrun false;
list* p1=head;
list* p2=head->next;
while(p1!=p2)
{
p1=p1->next;
if(p2->next)
p2=p2->next;
else
return false;

if(p1==p2) return true;

if(p2->next)
p2=p2->next;
else
return false;
}
return true;
}

No comments:

Post a Comment