Data structures 链表:检测循环

Data structures 链表:检测循环,data-structures,Data Structures,你好。。我试图从hackerrank那里解决这个问题。对于所有的输入条件,我得到了False。我想不出哪里出了问题。目标是检测linkedlist中的循环。这里是问题的链接 请帮忙 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:

你好。。我试图从hackerrank那里解决这个问题。对于所有的输入条件,我得到了False。我想不出哪里出了问题。目标是检测linkedlist中的循环。这里是问题的链接 请帮忙

    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

请标记一种语言,您将
slow
fast
初始化为
head
以便
而((slow!=fast))
将为
false
且循环从未进入。可能会有帮助-哦,耶。。我添加了一个do-while循环,它通过了所有测试条件。谢谢您的时间。:)