Detect Cycle in Linked List SOLUTION HACKER RANK

Detect Cycle in Linked List SOLUTION

Note 
After first solving the problem by yourself, see Floyd’s cycle-finding algorithm for an efficient solution which uses O(N) time and O(1) additional memory.
 
/*
  Detect loop in a linked list 
  List could be empty also
  Node is defined as 
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
int HasCycle(Node* head)
{
   // Complete this function
   // Do not write the main method
    if(head == NULL || head->next == NULL || head->next->next == NULL){
        return 0;
    }
    Node* slow = head;
    Node* fast = head->next->next;
    while(fast->next->next != NULL && slow->next != NULL){
        if(fast == slow){
            return 1;
        }else{
            fast = fast->next->next;
            slow = slow->next;
        }
    }
    return 0;
}

Leave a Comment

close
error: Content is protected !!