Repeat Exercise P15.6, but use a different implementation strategy. Remove the reference to the first node in the LinkedList class, and make the next reference of the last node point to the first node, so that all nodes form a cycle. Such an implementation is called a circular linked list.

Complete the following file:

Use the following file:

AddTester.java

/**
   A tester program for a revised version of the LinkedList class.
*/
public class AddTester
{  
   public static void main(String[] args)
   {  
      LinkedList names = new LinkedList();
      
      names.addFirst("Tom");
      names.addFirst("Harry");
      names.addFirst("Dick");

      names.add("Romeo");
      printList(names);
      System.out.println("Expected: Dick Harry Tom Romeo");

      // Remove last element and check that add still works
      ListIterator iterator = names.listIterator();
      while (iterator.hasNext()) iterator.next();
      iterator.remove();

      names.add("Juliet");
      printList(names);
      System.out.println("Expected: Dick Harry Tom Juliet");

      iterator = names.listIterator();
      // Add after last element and check that add still works
      while (iterator.hasNext()) iterator.next();
      iterator.add("Emily");
      names.add("Charlotte");
      printList(names);
      System.out.println("Expected: Dick Harry Tom Juliet Emily Charlotte");

      // Remove everything and check that add still works
      while (names.listIterator().hasNext())
         names.removeFirst();
      names.add("Nina");
      printList(names);
      System.out.println("Expected: Nina");

      names.removeFirst();
      names.addFirst("Adam");
      names.add("Eve");
      printList(names);
      System.out.println("Expected: Adam Eve");
      
      // Testing return values of removeFirst and getFirst
      System.out.println(names.removeFirst());
      System.out.println("Expected: Adam");
      System.out.println(names.getFirst());
      System.out.println("Expected: Eve");      
   }
   
   private static void printList(LinkedList list)
   {
      ListIterator iterator = list.listIterator();
      while (iterator.hasNext())
      {
         System.out.print(iterator.next() + " ");
      }
      System.out.println();
   }
}