// pqueue.cc
#include <stdlib.h>
#include "pqueue.h"

PQueue::PQueue(reallong (* v)(void *)) {
   valfn  = v;
   head = tail = NULL;
}

void PQueue::insert(void *t) {
   if (head == NULL) { head = tail = new Cell(t, NULL); return; }
   if (valfn(t) < valfn(head->item)) {
      head = new Cell(t, head);
      return;
   }
   Cell *ptr;
   for (ptr = head ; ptr->next != NULL ; ptr = ptr->next) {
      if (valfn(t) < valfn(ptr->next->item)) {
	 ptr->next = new Cell(t, ptr->next);
	 return;
      }
   }
   tail = new Cell(t, NULL);
   ptr->next = tail;
}

void PQueue::enqueue(void *t) {
   if (t == NULL) return;
   Cell *h = new Cell(t, NULL);
   if (head == NULL) head = h;
   else tail->next = h;
   tail = h;
}

void *PQueue::dequeue() {
   if (head == NULL) return NULL;
   Cell *ptr = head;
   void *t = head->item;
   head = head->next;
   delete ptr;
   if (head == NULL) tail = NULL;
   return t;
}

bool PQueue::empty()  {  return head == NULL;  }