Java Program to Detect loop in a LinkedList

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Detect Loop in a LinkedList

Output

LinkedList: 1 2 3 4 
There is a loop in LinkedList.

In the above example, we have implemented a LinkedList in Java. We have used Floyd's cycle finding algorithm to check if there is a loop in LinkedList.

Notice the code inside the checkLoop() method. Here, we have two variables named first and second that traverse the nodes in LinkedList.

  • first - traverse with 2 nodes at single iteration
  • second - traverse with 1 node at single iteration

Two nodes are traversing at different speeds. Hence, they will meet if there is a loop in LinkedList.