package plp.collection; /** * A list with cursor. * Elements are inserted or removed following the position of the cursor. * This version implements a position facility. */ public class CList { private int size; private Cell cursor; private Cell first; private Cell end; public CList() { size = 0; first = new Cell(); end = new Cell(first, null); cursor = first; } public int size() { return size; } public boolean empty() { return size == 0; } public void insert(Object o) { cursor = new Cell(cursor, o, cursor.next()); size ++; } private void checkNotEnd() { if (atEnd()) { throw new Error("Invalid position"); } } private void checkNotFirst() { if (atFirst()) { throw new Error("Invalid position"); } } public void replace(Object o) { checkNotEnd(); cursor.next().setData(o); } public void remove() { checkNotEnd(); cursor.next().remove(); size --; } public void goFirst() { cursor = first; } public void goEnd() { cursor = end.prev(); } public void goTo(Position pos) { if (!pos.isValid()) { throw new Error("Invalid Position"); } cursor = (Cell)pos; } public Position getPosition() { return cursor; } public boolean atFirst() { return cursor == first; } public boolean atEnd() { return cursor == end.prev(); } public void forward() { checkNotEnd(); cursor = cursor.next(); } public void backward() { checkNotFirst(); cursor = cursor.prev(); } public Object get() { checkNotEnd(); return cursor.next().data(); } public String toString() { String s = "cursor = " + cursor + "\n"; for (Cell c = first.next(); c != end; c = c.next()) { s += c + "\n"; } return s; } }