How to detect loop in a linked list in java with example

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
One of the most popular interview question nowadays is "How to detect loop/cycle in LinkedList". So I thought I should cover this question. This question is more related to data structure. You can also find start node of loop if loop exists.

Java Linked List Interview Programs:

    How to reverse a linked list in java How to reverse a linked list in pairs in java How to find middle element of linked list in java How to detect a loop in linked list in java Find start node of loop in linkedlist How to find nth element from end of linked list How to check if linked list is palindrome in java Add two numbers represented by linked list in java

First approach that you may think may something look like:
  • Traverse through each node till end , tracking visited node using visited flag.
  • If you find node that is already visited, then there is a loop in LinkedList and if you reach till end while traversing then there is no loop in LinkedList
But problem with above approach is, in most cases you can not change data structure of LinkedList node, so you won't be able to add visited flag to it.

Efficient approach:

Efficient approach for this problem would be Floyd's cycle detection algorithm,so steps for this algo would be:
  • Use two pointer fastPtr and slowPtr and initialize both to head of linkedlist
  • Move fastPtr by two nodes and slowPtr by one node in each iteration.
  • If fastPtr and slowPtr meet at some iteration , then there is a loop in linkedlist.
  • If fastPtr reaches to the end of linkedlist without meeting slow pointer then there is no loop in linkedlist (i.e fastPtr->next or fastPtr->next->next become null)

Java code for this algo will be 
 public boolean ifLoopExists() {
  Node fastPtr = head;
  Node slowPtr = head;
  while (fastPtr != null && fastPtr.next != null) {
   fastPtr = fastPtr.next.next;
   slowPtr = slowPtr.next;
   if (slowPtr == fastPtr)
    return true;

  }
  return false;
 }
Above solution work with o(n) time complexity and o(1) space complexity.

Lets create linked list without loop :

Lets create a java program called "LinkedList.java"

package org.arpit.java2blog;

public class LinkedList{

 private Node head;

 private static class Node {
  private int value;
  private Node next;

  Node(int value) {
   this.value = value;
  
  }
 }

 public void addToTheLast(Node node) {
  
  if (head == null) {
   head = node;
  } else {
   Node temp = head;
   while (temp.next != null)
    temp = temp.next;

   temp.next = node;
  }
 }

 
 public void printList() {
  Node temp = head;
  while (temp != null) {
   System.out.format("%d ", temp.value);
   temp = temp.next;
  }
  System.out.println();
 }

 public boolean ifLoopExists() {
  Node fastPtr = head;
  Node slowPtr = head;
  while (fastPtr != null && fastPtr.next != null) {
   fastPtr = fastPtr.next.next;
   slowPtr = slowPtr.next;
   if (slowPtr == fastPtr)
    return true;

  }
  return false;
 }

 public static void main(String[] args) {
  LinkedList list = new LinkedList();
  // Creating a linked list
  
  list.addToTheLast(new Node(5));
  list.addToTheLast(new Node(6));
  list.addToTheLast(new Node(7));
  list.addToTheLast(new Node(1));
  list.addToTheLast(new Node(2));
  
  
  list.printList();
  
    // Test if loop existed or not
  System.out.println("Loop existed-->" + list.ifLoopExists());

 }
}

Logically our linkedlist can be represented as :



Run above program, you will get following output:
5 6 7 1 2 
Loop existed-->false

Lets create a loop in linkedlist

Now we will connect last node to the nodewith value 7 and it will create loop in linked list, so change above main method to this:
public static void main(String[] args) {
  LinkedList list = new LinkedList();
  // Creating a linked list
  Node loopNode=new Node(7);
  list.addToTheLast(new Node(5));
  list.addToTheLast(new Node(6));
  list.addToTheLast(loopNode);
  list.addToTheLast(new Node(1));
  list.addToTheLast(new Node(2));
  
  list.printList();
  // creating a loop
  list.addToTheLast(loopNode);
    // Test if loop existed or not
  System.out.println("Loop existed-->" + list.ifLoopExists());

 }
Logically our linkedlist with loop can be represented as :



Run above program, you will get following output:
5 6 7 1 2 
Loop existed-->true
so this is how you can detect a loop in linkedlist.

Please go through java interview programs for more such programs.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012