package plp.collection; /** * A list with cursor. * Elements are inserted or removed following the position of the cursor. */ public class CList { private int size; private Cell cursor; private Cell first; private Cell last; public CList() { size = 0; cursor = first = last = null; } public int size() { return size; } public boolean empty() { return size == 0; } public void insert(Object o) { if (atFirst()) { first = cursor = new Cell(null, o, first); } else { cursor = new Cell(cursor, o, cursor.next()); } if (cursor.next() == null) { last = cursor; } 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(); if (atFirst()) { Cell second = first.next(); first.remove(); first = second; } else { if (cursor.next() == last) { last = cursor; } cursor.next().remove(); } size --; } public void goFirst() { cursor = null; } public void goEnd() { cursor = last; } public boolean atFirst() { return cursor == null; } public boolean atEnd() { return cursor == last; } public void forward() { checkNotEnd(); cursor = atFirst() ? first : cursor.next(); } public void backward() { checkNotFirst(); cursor = cursor.prev(); } public Object get() { checkNotEnd(); return atFirst() ? first.data() : cursor.next().data(); } public String toString() { String s = "cursor = " + cursor + "\n"; for (Cell c = first; c != null; c = c.next()) { s += c + "\n"; } return s; } }