链接列表:检测周期

时间:2017-04-13 17:21:03

标签: data-structures

  

您好..我试图从hackerrank解决这个问题。对于所有输入条件,我得到False。无法弄清楚我哪里出错了。目标是检测链表中的循环。以下是问题https://www.hackerrank.com/challenges/ctci-linked-list-cycle的链接   请帮忙。

    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

0 个答案:

没有答案