// Textbook fragment 06.19 /** List of favorite elements, with their access counts. */ public class FavoriteList { protected PositionList> fList; // List of entries /** Constructor; O(1) time */ public FavoriteList() { fList = new NodePositionList>(); } /** Returns the number of elements in the list; O(1) time */ public int size() { return fList.size(); } /** Returns whehter the list is empty; O(1) time */ public boolean isEmpty() { return fList.isEmpty(); } /** Removes a given element, provided it is in the list; O(n) time */ public void remove(E obj) { Position> p = find(obj); // search for obj if (p != null) fList.remove(p); // remove the entry } /** Increments the access count for the given element and inserts it * if it is not already present; O(n) time */ public void access(E obj) { Position> p = find(obj); // find the position of obj if (p != null) p.element().incrementCount(); // increment access count else { fList.addLast(new Entry(obj)); // add the new entry at the end p = fList.last(); } moveUp(p); // moves the entry to its final position } /** Finds the position of a given element, or returns null; O(n) time */ protected Position> find(E obj) { for (Position> p: fList.positions()) if (value(p).equals(obj)) return p; // fount at position p return null; // not found } /** Moves up an entry to its correct position in the list; O(n) time */ protected void moveUp(Position> cur) { Entry e = cur.element(); int c = count(cur); while (cur != fList.first()) { Position> prev = fList.prev(cur); // previous position if (c <= count(prev)) break; // entry is at correct position fList.set(cur, prev.element()); // move down previous entry cur = prev; } fList.set(cur, e); // store the entry in its final position }