In: Computer Science
You are given a singly linked list. Write a function to find if the linked list contains a cycle or not. A linked list may contain a cycle anywhere. A cycle means that some nodes are connected in the linked list. It doesn't necessarily mean that all nodes in the linked list have to be connected in a cycle starting and ending at the head. You may want to examine Floyd's Cycle Detection algorithm.
/*This function returns true if given linked list has a cycle, else returns false. */ static boolean hasCycle( Node head)
The java code to find the loop or cycle in the linked list which may be present at any place in the linked list.
For the function to find the cycle is present or not we use Floyd's Cycle Detection algorithm.
static boolean hasCycle(Node head){
Node slow_node=head;
Node fast_node=head;
while(slow_node != null && fast_node !=null && fast_node.next !=null){
slow_node = slow_node.next;
fast_node = fast_node.next.next;
if(slow_node==fast_node){
System.out.println("Cycle is present");
return true;
}
}
return flase;
}
In this code, we first take two nodes slow and fast. Assign the linked list head value to them and start the algorithm condition. By checking the conditions of null we run the while loop which increases the value of slow node by next and fast node by next, next. If there is loop then definitely this fast and slow values will be equal and we can find the loop is present.
I have not written code about Node or main function as it is not required according to the question given.
I hope you got the answer and understand it. Any doubts ask in comments I will help with it.
Thank you:):)