How to detect a loop in a linked list in java?

How to detect a loop in a linked list in java?

Detecting a loop in a linked list is a common problem in computer science. You can use Floyd's Tortoise and Hare algorithm, also known as the "Cycle Detection" algorithm, to determine whether a loop exists in a linked list. Here's how to implement it in Java:

class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; this.next = null; } } public class LinkedListCycleDetection { public boolean hasCycle(ListNode head) { if (head == null || head.next == null) { return false; // No cycle if there are fewer than two nodes } ListNode slow = head; // Tortoise ListNode fast = head; // Hare // Move slow one step and fast two steps until they meet or fast reaches the end while (fast != null && fast.next != null) { slow = slow.next; // Move one step fast = fast.next.next; // Move two steps if (slow == fast) { return true; // Cycle detected } } return false; // No cycle found } public static void main(String[] args) { // Create a sample linked list with a cycle ListNode head = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); ListNode node5 = new ListNode(5); head.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node2; // Create a cycle LinkedListCycleDetection solution = new LinkedListCycleDetection(); boolean hasCycle = solution.hasCycle(head); if (hasCycle) { System.out.println("The linked list contains a cycle."); } else { System.out.println("The linked list does not contain a cycle."); } } } 

In this code:

  • We define a ListNode class to represent the nodes of the linked list.

  • The hasCycle method uses two pointers, slow and fast, initialized to the head of the linked list.

  • The while loop advances slow by one step and fast by two steps in each iteration. If there is a loop in the linked list, the two pointers will eventually meet (slow == fast). If there is no loop, the fast pointer will reach the end of the list (fast == null || fast.next == null).

  • If a cycle is detected, the method returns true. Otherwise, it returns false.

  • In the main method, we create a sample linked list with a cycle for testing the algorithm.

This algorithm works efficiently with a time complexity of O(n) and a space complexity of O(1), where n is the number of nodes in the linked list.


More Tags

android-widget procfs google-picker openpgp heartbeat dagger tf-idf external entity-framework-6.1 iphone-web-app

More Java Questions

More Electrochemistry Calculators

More Various Measurements Units Calculators

More Genetics Calculators

More Stoichiometry Calculators