#include #include #include #include "Pq.h" #define INITIAL_CAPACITY 8 struct pq { struct pqItem *items; int numItems; int capacity; }; struct pqItem { int item; int priority; }; static void resize(Pq pq); Pq PqNew(void) { Pq pq = malloc(sizeof(struct pq)); if (pq == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } pq->numItems = 0; pq->capacity = INITIAL_CAPACITY; pq->items = malloc(pq->capacity * sizeof(struct pqItem)); return pq; } void PqFree(Pq pq) { // TODO free(pq->items); free(pq); } void PqInsert(Pq pq, int item, int priority) { if (pq->numItems == pq->capacity) { resize(pq); } // TODO // Move along the array and find the spot our new element belongs int i=pq->numItems-1; while(i >= 0 && pq->items[i].priority > priority) { pq->items[i+1].item = pq->items[i].item; pq->items[i+1].priority = pq->items[i].priority; i--; } i++; // i is now at the point to insert the item pq->items[i].item = item; pq->items[i].priority = priority; pq->numItems++; } static void resize(Pq pq) { pq->capacity *= 2; pq->items = realloc(pq->items, pq->capacity * sizeof(struct pqItem)); if (pq->items == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } } int PqDelete(Pq pq) { if (pq->numItems == 0) { fprintf(stderr, "error: pq is empty\n"); exit(EXIT_FAILURE); } // TODO pq->numItems--; return pq->items[pq->numItems].item; } int PqPeek(Pq pq) { if (pq->numItems == 0) { fprintf(stderr, "error: pq is empty\n"); exit(EXIT_FAILURE); } // TODO return pq->items[pq->numItems-1].item; }