Saturday, 18 April 2015

Hackerrank Detect Cycle solution

Problem Statement

This challenge is part of a tutorial track by MyCodeSchool

You’re given the pointer to the head node of a linked list. Find whether the list contains any cycle (or loop). A linked list is said to contain cycle if any node is re-visited while traversing the list. The head pointer given may be null meaning that the list is empty.

Source Code:

  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  
   Node* fast = head, *slow = head;  
   while(fast!= NULL){  
     fast = fast->next->next;  
     slow = slow->next;  
     if(fast == slow){  
       return 1;  
   }return 0;  

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

1 comment:

  1. it wont work for a large no. of critical cases
    1->2->3->4->linked back to 2