Take 2 pointer. increment 1 pointer once and another pointer twice.
keep incrementing unless pointer2 is NULL or when pointer 1 and pointer 2 are equal.
When both pointer equal there is a Loop existing.
otherwise no Loop Detected.
/* Source Code */
/* Assume that there is a linked list which is already existing */
void findLoop()
{
struct llist *ptr1 *ptr2;
ptr1 head;
ptr2 head->link;
if(ptr1 ptr2)
printf("nLoop Detectedn");
else
{
while((ptr2 ! NULL) && (ptr1 ! ptr2))
{
ptr1 ptr1->link;
ptr2 ptr2->link;
if(ptr2 ! NULL)
ptr2 ptr2->link;
}
if(ptr2 NULL)
printf("Loop is not Detectedn");
else
{
if(ptr1 ptr2)
{
printf("Loop Detectedn");
}
}
}
}