#include #include #include "priority_queue.h" #include "error.h" PositionPQ *ppq_new(Position pos, size_t priority) { PositionPQ *ppq = malloc(sizeof(PositionPQ)); ppq->pos = pos; ppq->priority = priority; ppq->next = NULL; return ppq; } /* TODO: we need to handle if a pos is already in ppq, but this time we have it with better priority. * I think we need to implement ppq_remove(*ppq, pos), which'll see if pos is in ppq and will remove it. * Then we call it where we return PPQ_INSERT_SUCCESS, but before we actually insert the pos. */ int ppq_insert(PositionPQ **ppq, Position pos, size_t priority) { //printf("Inserting %zu %zu\n", pos.x, pos.y); PositionPQ *start = *ppq; if ((*ppq) == NULL) { (*ppq) = ppq_new(pos, priority); return PPQ_INSERT_NEW; } PositionPQ *n = ppq_new(pos, priority); if (start->priority > priority) { n->next = start; start = n; return PPQ_INSERT_SUCCESS; } PositionPQ *temp = *ppq; while(temp->next != NULL && temp->next->priority <= priority) { if (temp->pos.x == pos.x && temp->pos.y == pos.y && temp->priority <= priority) { free(n); return PPQ_INSERT_ALREADY; } temp = temp->next; } if (temp->pos.x == pos.x && temp->pos.y == pos.y && temp->priority <= priority) { free(n); return PPQ_INSERT_ALREADY; } n->next = temp->next; temp->next = n; return PPQ_INSERT_SUCCESS; } Position ppq_pop(PositionPQ **ppq) { if (*ppq == NULL) { error("Tried to pop a NULL PositionPQ\n"); } Position pos = (*ppq)->pos; if ((*ppq)->next != NULL) { /* If there's a next node */ PositionPQ *next = (*ppq)->next; free((*ppq)); (*ppq) = next; } else { /* No next node */ free((*ppq)); (*ppq) = NULL; } return pos; } void ppq_reprioritize(PositionPQ *ppq, Position pos, size_t priority) { (void)ppq, (void)pos, (void)priority; todo(); } void ppq_print(PositionPQ *ppq) { if (ppq == NULL) { printf("ppq is NULL\n"); return; } int i = 0; while (ppq->next != NULL) { printf("%i - %li: %li, %li\n", i++, ppq->priority, ppq->pos.x, ppq->pos.y); ppq = ppq->next; } printf("%i - %li: %li, %li\n", i++, ppq->priority, ppq->pos.x, ppq->pos.y); } void ppq_free(PositionPQ *ppq) { if (ppq == NULL) return; while(ppq->next != NULL) { PositionPQ *t = ppq; ppq = ppq->next; free(t); } if (ppq != NULL) free(ppq); }