Detect Loop in a Linked List in Java



In this article, we will understand how to detect a loop in a LinkedList using Java. When traversing a linked list, we start from the head node and keep moving to the next node until we reach the end of the list, where the next pointer is null. In the case of a loop, instead of reaching the end of a list, we end up at the same point we have already been to, forming a loop.

What is LinkedList?

A linked list is a sequence of data structures where each node contains two parts ?

  • Data - The value or information stored in the node.
  • Next - A reference (or pointer) to the next node in the sequence.

What is a loop in LinkedList?

A loop means that the last node of a linked list is connected back to a node earlier in the list, creating a cycle. This causes infinite traversal during list operations.

Different methods to detect a loop

The following are the different methods for detecting if there is a loop in the linked list ?

Using HashSet to Detect a Loop

HashSet: A HashSet is a collection class in Java that implements the set interface. It is part of the java.util package and is used to store a unique collection of elements.

Step 1 - Node Creation

  • The Node class is used to define the structure of each node in the linked list. Each node contains two components: data to hold the value and next to point to the subsequent node in the list.

Step 2 - Linked List Construction

  • The push method is used to insert new nodes at the head of the linked list. This allows for the addition of elements while maintaining the structure of the linked list.

Step 3 - Loop Detection Using HashSet

  • The check_loop method uses a HashSet to detect loops in the linked list. As the list is traversed, each node is checked against the HashSet. If a node is already present in the set, it indicates a loop, and the method returns true. If the node is not present, it is added to the set, and the traversal continues. If the traversal ends (head == null), the method returns false, confirming no loop.

Java program to detect a loop in a LinkedList using HashSet

Below is an example of detecting a loop in a LinkedList using HashSet ?
import java.util.*;
public class Demo {
	static Node head;
	static class Node {
		int data;
		Node next;
		Node(int d) {   //  Node creation
			data = d;
			next = null;
		}
	}
	static public void push(int new_data) { // Linked List Construction
		Node new_node = new Node(new_data);
		new_node.next = head;
		head = new_node;
	}                                                                                                                 
	static boolean check_loop(Node head) {    // Loop Detection Using HashSet
		HashSet<Node> s = new HashSet<Node>();
		while (head != null) {
			if (s.contains(head))
				return true;
			s.add(head);
			head = head.next;
		}
		return false;
	}
	public static void main(String[] args) {
		System.out.println("The required packages have been imported");
		Demo input_list = new Demo();
		input_list.push(45);
		input_list.push(60);
		input_list.push(75);
		input_list.push(90);
		input_list.head.next.next.next.next = input_list.head;
		if (check_loop(head))
			System.out.println("The loop exists in the linked list");
		else
			System.out.println("The loop doesnot exists in the linked list");
	}
}

Output

The required packages have been imported
The loop exists in the linked list

Using Floyd's cycle algorithm to detect a loop

Floyd's Cycle Detection Algorithm, also known as the Tortoise and Hare algorithm, is a method used to detect cycles or loops in a linked list or a sequence. 

It uses two pointers:

  • The slow pointer moves one step at a time.
  • The fast pointer moves two steps at a time.

In this algorithm, one moves one step at a time (slow), and the other moves two steps at a time (fast). If there is a loop in the list, the fast pointer will meet with the slow pointer inside the loop.

  • The check_loop method uses two pointers, first_node, and second_node, to detect a loop.
  • first_node moves two steps at a time, and second_node moves one step at a time.
  • If the two pointers meet at any point, it confirms the presence of a loop.
  • If first_node reaches the end of the list (null), it indicates no loop, and the method returns false.

Java program to detect a loop in a LinkedList using Floyd's cycle detection algorithm

Below is an example of detecting a loop in a LinkedList using Floyd's cycle detection algorithm ?

public class Demo {
	Node head;
	static class Node {
		int value;
		Node next;
		Node(int d) {       // Constructor to initialize the node
			value = d;
			next = null;
		}
	}
	public boolean check_loop() {   //using Floyd's Cycle Detection
		Node first_node = head;
		Node second_node = head;
		while(first_node != null && first_node.next !=null) {
			first_node = first_node.next.next;
			second_node = second_node.next;
			if(first_node == second_node) {
				return true;
			}
		}
		return false;
	}
	public static void main(String[] args) {
		Demo input_list = new Demo();
		input_list.head = new Node(45);
		Node second_node = new Node(60);
		Node third_node = new Node(75);
		Node fourth_node = new Node(90);
		input_list.head.next = second_node;
		second_node.next = third_node;
		third_node.next = fourth_node;
		fourth_node.next = second_node;
		System.out.print("The elements of the linked list are: ");
		int i = 1;
		while (i <= 4) {
			System.out.print(input_list.head.value + " ");
			input_list.head = input_list.head.next;
			i++;
		}
		boolean loop = input_list.check_loop();
		if(loop) {
			System.out.println("\nThere is a loop in the linked list.");
		}
		else {
			System.out.println("\nThere is no loop in the linked list.");
		}
	}
}

Output

The elements of the linked list are: 45 60 75 90
There is a loop in the linked list.
Updated on: 2024-11-20T22:42:06+05:30

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements