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
Asked
Active
Viewed 154 times
0

shailuk
- 11
- 5
-
Please tag a language – 001 Apr 13 '17 at 17:25
-
2You initialize `slow` and `fast` to `head` so`while( (slow != fast) )` will be `false` and the loop never entered. – 001 Apr 13 '17 at 17:27
-
May be helpful - http://stackoverflow.com/a/32190575/1835769 – displayName Apr 13 '17 at 17:48
-
oh ya.. I added a do while loop and it passed all test conditions. thanks for your time.:) – shailuk Apr 13 '17 at 17:51