import java.util.Iterator; import java.util.Random; public class ListWithLoopDetection implements Iterable { public static final int MAX_ITEMS_TO_PRINT = 30; private class Node { Item item; Node next; } // YOU MAY ADD EXACTLY ONE INSTANCE VARIABLE, IF NEEDED public void addItem(Item item) { // ADD CODE HERE } public void insertLoopToPosition(int pos) { // ADD CODE HERE } // YOU MAY ADD EXACTLY ONE ADDITIONAL METHOD HERE, IF NEEDED public boolean loopExists() { // ADD CODE HERE } public static void main(String[] args) { Random random = new Random(); // Your code must NOT rely on this to work, but we choose // to test the code with lists small enough that when // printed, it will be obvious if a loop exists int numItems = 1 + random.nextInt(MAX_ITEMS_TO_PRINT / 2); // make list of n integers (0 through (n-1)) ListWithLoopDetection list = new ListWithLoopDetection(); for (int i = 0; i < numItems; i++) { list.addItem(i); } // half of the time (at random) put in a loop if (random.nextBoolean()) { list.insertLoopToPosition(random.nextInt(numItems)); } // print the list int count = 0; for (Integer i : list) { if (count > MAX_ITEMS_TO_PRINT) { System.out.print("..."); break; } System.out.printf("%d ",i); count++; } System.out.println(); // detect a loop, if present System.out.println(list.loopExists() ? "Loop Exists" : "No Loop Exists"); } }