0

Hello.. I was trying to solve this question from hackerrank. I am getting False for all the Input condition. Can't figure out where I am going wrong. The objective is detect loops in a linkedlist. Here is the link to the problem https://www.hackerrank.com/challenges/ctci-linked-list-cycle Please help.

    My solution is :

    /*
    Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty.

    A Node is defined as: 
        class Node {
            int data;
            Node next;
        }
    */

    boolean hasCycle(Node head) {

        int counter = 0;

       if(head == null || head.next == null)  
//if the list is empty or if there is only one node in the list
           {
           return false;
       }else
           {
           Node slow = head;  //initialize both the pointers to head
           Node fast = head;

           while( (slow != fast)  )    //loop if slow and fast are not equal 
               {

               slow = slow.next;   //slow shifts by 1
               fast = fast.next.next;  //fast shifts by 2

               if( (fast == null ) )   //when fast reaches null, there is no cycle
                   {
                   counter = 0;  //false, no cycle
                      break;

               } //end of inner if stmt
               else if(slow == fast)  
//when both the the pointers meet, there is a cycle
                   {
                   counter = 1;   //true, there is cycle
                   break;
               } //end of inner else stmt

           } //end of while loop

       } //end of else stmt
           if(counter == 0)
               {
               return false;
           }
           return true;

    }  //end of method
shailuk
  • 11
  • 5

0 Answers0