voidptrdance

Example code for a blog post on generic programming in C
git clone https://git.tronto.net/voidptrdance
Download | Log | Files | Refs | README

PriorityQueue.c (746B)


      1 #include <stdlib.h>
      2 #include "PriorityQueue.h"
      3 
      4 typedef struct {
      5 	T e[255];
      6 	int n;
      7 } QData;
      8 
      9 PriorityQueue *NewPriorityQueue(TDescription desc) {
     10 	PriorityQueue *q = malloc(sizeof(PriorityQueue));
     11 	q->desc = desc;
     12 	q->data = malloc(sizeof(QData));
     13 	((QData *)q->data)->n = 0;
     14 	return q;
     15 }
     16 
     17 void Add(PriorityQueue *q, T t) {
     18 	QData *qdata = (QData *)q->data;
     19 	qdata->e[qdata->n++] = t;
     20 }
     21 	
     22 T Pop(PriorityQueue *q) {
     23 	QData *qdata = (QData *)q->data;
     24 	if (qdata->n == 0) return NULL;
     25 	int i, itop = 0;
     26 	for (i = 0; i < qdata->n; i++)
     27 		if (q->desc.priority(qdata->e[i]) >
     28 		    q->desc.priority(qdata->e[itop]))
     29 			itop = i;
     30 	T top = qdata->e[itop];
     31 	for (int j = i; j < qdata->n-1; j++)
     32 		qdata->e[j] = qdata->e[j+1];
     33 	qdata->n--;
     34 	return top;
     35 }