English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to detect if there is a loop in a LinkedList in Java.
To understand this example, you should be familiar with the followingJava ProgrammingTopic:
class LinkedList { //Create an object of Node class //Represents the head of the linked list Node head; //Static inner class static class Node { int value; //Connect each node to the next node Node next; Node(int d) { value = d; next = null; } } //Check if there is a loop public boolean checkLoop() { //Create two references at the beginning of LinkedList Node first = head; Node second = head; while (first != null && first.next != null) { //Move the first reference2a node first = first.next.next; //Move the second reference1a node second = second.next; //If two references are equal (encountered) if (first == second) { return true; } } return false; } public static void main(String[] args) { //Create a LinkedList object LinkedList linkedList = new LinkedList(); //Assign values to each linked list node linkedList.head = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); //Connect each node of the linked list to the next node linkedList.head.next = second; second.next = third; third.next = fourth; //Loop in LinkedList fourth.next = second; //Print node value System.out.print("LinkedList: "); int i = 1; while (i <= 4) { System.out.print(linkedList.head.value + ""); linkedList.head = linkedList.head.next; i++; } //Call method to check for loop boolean loop = linkedList.checkLoop(); if(loop) { System.out.println("\nThere is a loop in LinkedList."); } else { System.out.println("\nThere is no loop in LinkedList."); } } }
Output Result
LinkedList: 1 2 3 4 There is a loop in LinkedList.
. In the above example, we have used Java to implement LinkedList. We usedFloyd's Cycle Detection Algorithmto check if there is a loop in LinkedList.
Note the code in the checkLoop() method. Here, we have two variables named first, second, which traverse the nodes in LinkedList.
first - in a single iteration2nodes for traversal
second - in a single iteration1nodes for traversal.
Two nodes traverse at different speeds. Therefore, if there is a loop in LinkedList, they will meet.