Best Solution
--------------
loop(node *ptr)
{
node *temp1,*temp2;
temp1=ptr;
if (temp1) {
temp2=temp1->next;
}
while(temp1 && temp2 && temp2->next && temp1 != temp2)
{
temp1==temp1->next;
temp2=temp2->next->next;
}
if(temp1==temp2)
printf("The loop exist\n")
else
printf("There exist no loop\n");
}
My solution
-----------Just Pseudo Code onlyRegarding finding a loop inside a linked list, If setting a flag in the
list * visited_list[BIG_ARRAY] ={0};
int any_loops( list * p)
{
if ( p == null ) return 0; // means no loops
search for "p" in "visited_list"
if present
return 1; // means loop identified.
add p in "visited_list".
return any_loops (p->next)
}
You may use "visited_list" as another linked list instead of array.
Another solution
---------------
node is allowed (which is initially reset) then the following will be
better.
This doesn't need recursion or any search inside the array which may be
time consuming.
int findloop(node_t *head)
{
while (head != NULL) {if (!head->visited) {
head->visited =1;
head = head->next;
}
else {
printf("found a loop in the linked list\n");
return 1;
}
}
printf("no loop found in the linked list\n");
return 0;
}
Subscribe to Post Comments [Atom]
July 2005 August 2005 October 2005 December 2005 March 2006 June 2006 July 2006 December 2006 February 2007 June 2007 March 2010 May 2010
Subscribe to Posts [Atom]