import cs101.terminal.*; public class ListOfInts { 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 ListOfInts() { head = rear = marker = new ListItem(0, null); // create dummy } public boolean isEmpty() { return (head.next == null); // alternatively, (head == rear) } public ListOfInts prepend(int n) { head.next = new ListItem(n, head.next); if (head == rear) // check if this is also the last item rear = head.next; return this; } public ListOfInts append(int n) { rear.next = new ListItem(n, null); rear = rear.next; return this; } public boolean atEnd() { return (marker.next == null); } public void reset() { marker = head; } public ListOfInts next() { if (!atEnd()) marker = marker.next; return this; } public int getItem() { // gets current item if (atEnd()) Terminal.println("Error: Tried to get item past end of list!"); else return marker.next.number; } public void setItem(int n) { // replaces value of current item if (atEnd()) Terminal.println("Error: Tried to set item past end of list!"); else marker.next.number = n; } public void insert(int n) { // inserts n just before the current item, and // the new item n becomes the current item if (atEnd()) // appends the item if marker is at the end append(n); else marker.next = new ListItem(n, marker.next); } public int delete() { // deletes the current item if (atEnd()) { Terminal.println("Error: Tried to delete item past end of list!"); return 0; } else { result = marker.next.number; if (marker.next == rear) rear = marker; marker.next = marker.next.next; return result; } } public String toString() { if (isEmpty()) return "( )"; else return "(" + head.next + " )"; } } class ListItem { public int number; public ListItem next; ListItem(int number, ListItem next) { this.number = number; this.next = next; } public String toString() { if (this.next == null) return (" " + number); else return (" " + number + this.next); } }