/** * ListOfObjects class, patterned after ListOfInts * * You do not need to modify or turn in this file * * @author Robert A. Amar, Ron K. Cytron * @version 2.0 */ public class ListOfObjects { ListItem marker; // the current item is the one after the marker ListItem head; // always refers to the dummy ListItem rear; // always refers to the last item in the list public ListOfObjects() { head = rear = marker = new ListItem(null, null); // create dummy } public boolean isEmpty() { return head == rear; } public ListOfObjects prepend(Object n) { ListItem newHead = new ListItem(n, head.getNext()); head.setNext(newHead); if (isEmpty()) // check if this is also the last item rear = newHead; return this; } public ListOfObjects append(Object n) { ListItem newRear = new ListItem(n, null); rear.setNext(newRear); rear = newRear; return this; } public boolean atEnd() { return marker.getNext() == null; } public void reset() { marker = head; } public ListOfObjects next() { if (!atEnd()) marker = marker.getNext(); else throw new Error("Attempt to advance beyond end of list."); return this; } public Object getItem() { // gets current item if (isEmpty()) throw new Error("Attempt to get an item from an empty list."); else if (atEnd()) throw new Error("Attempt to get an item beyond end of list."); else return marker.getNext().getItem(); } public void setItem(Object n) { // replaces value of current item if (isEmpty()) throw new Error("Attempt to set an item in an empty list."); else if (atEnd()) throw new Error("Attempt to set an item beyond end of list."); else marker.getNext().setItem(n); } public void insert(Object n) { // inserts n just before the current item, and // the new item n becomes the current item if (atEnd()) append(n); else marker.setNext(new ListItem(n, marker.getNext())); } public Object delete() { // deletes the current item if (atEnd()) { throw new Error("Tried to delete item past end of list!"); } else { Object result = getItem(); if (marker.getNext() == rear) rear = marker; marker.setNext(marker.getNext().getNext()); return result; } } public String toString() { if (isEmpty()) return "( )"; else { ListItem first = head.getNext(); return "(" + first.toString() + " )"; } } }