top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to know if linklint has a loop?

+3 votes
623 views

Want to write the code in C to detect a loop in the link-list, please help.

posted Oct 22, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer
boolean isLoopList (list *head)
{
    list *ptr1, *ptr2;
    ptr1 = ptr2 = head;

    while(ptr2 && ptr2->next)
    {
        ptr2 = ptr2->next->next;
        ptr1 = ptr1->next ;
        if (ptr1 == ptr2)
            return TRUE;
    }
    return FALSE;
}
answer Oct 22, 2013 by Vikas Upadhyay
Hi, This wont work for semi-circular i guess, will this work  ?
Did you try :)
+1 vote

Am just sharing idea, not code.

Make two pointers such that pointer1 traverse 1 by 1, pointer 2 traverse by 2.

List is not circular if pointer 2 meets NULL [have to make check for this].

List is circular if pointer2 meets any of first 2 element [have to make check for this also].

Such that for even number of nodes pointer 2 meets first element [Have to take backup of first 2 elements]

@Experts, Let me know if you have alternate approach.

answer Oct 22, 2013 by sivanraj
Looks to be perfect solution, can you share the code also....
Similar Questions
+6 votes

What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.

+5 votes
      40
      /\
     20 60
     /\  \
   10 30  80
      /   /\
     25  70 90
           \
           75

longest path 
25 30 20 40 60 80 70 75 
Answer
    25 ----> 75
...