public static void hasLoop(Node first) { // If list is empty no loop exists if (first == null) { System.out.println("List empty!"); } // Set tortoise to the start of the list Node tortoise = new Node(first.getElement(), first.getNext()); // Set hare to next element Node hare = new Node(tortoise.getNext().getElement(), tortoise.getNext()); while (tortoise != hare) { // Move tortoise one position tortoise = tortoise.getNext(); // Move hare two positions if (hare == null) { System.out.println("No cycle found"); // reached the end, no cycle break; } else { hare = hare.getNext().getNext(); } // Cycle found if (tortoise == hare) { // Reset tortoise to start of list tortoise = new Node(first.getElement(), first.getNext()); int mu = 0; // Move tortoise and hare at one step each // Tortoise and hare will intersect again at start of cycle while (tortoise != hare) { tortoise = tortoise.getNext(); hare = hare.getNext(); mu += 1; } hare = tortoise.getNext(); int lam = 1; // Hare moves one step at a time until it meets tortoise // to determine the lenght of the cycle while (tortoise != hare) { hare = hare.getNext(); lam += 1; } // Feedback System.out.println("Cycle found!"); System.out.println("Cycle starts at: " + mu); System.out.println("Cycle length: " + lam); } } }