public class SortedSequencePriorityQueue implements PriorityQueue {
  protected Sequence S = new NodeSequence();
  protected Comparator comp;

  protected Object key (Position pos) {
    return ((Item) pos.element()).key();
  }
  protected Object elem (Position pos) {
    return ((Item) pos.element()).element();
  }
  protected Object elem (Object kep) {
    return ((Item) kep).element();
 }

  public SortedSequencePriorityQueue (Comparator c) { comp = c; }
  public int size () {return S.size(); }
  public boolean isEmpty () { return S.isEmpty(); }
  public void insertItem (Object k, Object e) throws InvalidKeyException {
    if (!comp.isComparable(k))
      throw new InvalidKeyException("The key is not valid");
    else if (S.isEmpty())
      S.insertFirst(new Item(k, e));
    else if (comp.isGreaterThan(k, key(S.last())))
      S.insertAfter(S.last(),new Item(k,e));
    else {
      Position curr = S.first();
      while (comp.isGreaterThan(k, key(curr)))
        curr = S.after(curr);
      S.insertBefore(curr,new Item(k,e));
    }
  }
  public Object removeMin() throws PriorityQueueEmptyException {
    if (S.isEmpty())
      throw new EmptyContainerException("The priority queue is empty");
    else
      return elem(S.remove(S.first()));
  }