Sunday, November 27, 2011

Acyclic Linked-List Detection Algorithm

Write a function that takes a pointer to the head of a list and determines whether the list is cyclic or acyclic. Your function should return false if the list is acyclic and true if it is cyclic. You may not modify the list in any way.

int determineTermination( node *head )
        { 
           node *fast, *slow;
           fast = slow = head; 
                  while( true )
                       {
                           if( !fast || !fast->next ) 
                              return false; 
                           else if( fast == slow || fast->next == slow ) 
                              return true; 
                           else 
                              {
                                 slow = slow->next; 
                                 fast = fast->next->next; 
                              }
                        }
        }


Leave your comments below the post.
Happy coding :)

No comments:

Post a Comment