How to check if linked list contains loop or cycle

In this post, we will check how to check if linked list contains loop or not.


Problem

We are given head of the linked list and we need to find loop in the linkedlist.

Solution

Here is simple algorithm to check if linked list contains loop or cycle.

  • Initialize two pointers slowPointer and fasterPointer
  • Move slowPointer by one node and fastPointer by two node
  • If slowPointer meets fastPointers then linked list contains loop
  • If fastPointer reaches to the end of linked list then linked list does not contain loop.


Complete java program to check loop in linked list

That’s all about finding loop in linked list.

Leave a Reply

Your email address will not be published. Required fields are marked *