zeroSquitto – Rev 1
?pathlinks?
/*************************************************************************/
/* Circular queue implementation. */
/*************************************************************************/
#include "circularQueue.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*************************************************************************/
/* Constructor with given size. */
/*************************************************************************/
CircularQueue *queueCreate(int size) {
CircularQueue *q = (CircularQueue *)calloc(1, sizeof(CircularQueue));
if ((q->store = (char **)calloc(size, sizeof(char *))) == NULL)
return NULL;
q->size = size;
q->head = 0;
q->tail = 0;
return q;
}
/*************************************************************************/
/* Enqueue an item to the queue. */
/*************************************************************************/
void queueEnqueue(CircularQueue *q, char *e) {
if (q->tail > q->size - 1)
q->store = (char **)realloc(q->store, ++q->size * sizeof(char *));
q->store[q->tail] = (char *)calloc(strlen(e) + 1, sizeof(char));
memcpy(q->store[q->tail], e, strlen(e) + 1);
++q->tail;
}
/*************************************************************************/
/* Dequeue an item off the queue. */
/*************************************************************************/
char *queueDequeue(CircularQueue *q) {
char *e;
if (queueIsEmpty(q))
return NULL;
e = (char *)calloc(strlen(q->store[q->head]) + 1, sizeof(char));
memcpy(e, q->store[q->head], strlen(q->store[q->head]) + 1);
queueEnqueue(q, e);
++q->head;
return e;
}
/*************************************************************************/
/* Clears the queue. */
/*************************************************************************/
CircularQueue *queueClear(CircularQueue *q) {
if (q != NULL)
free(q);
return queueCreate(1);
}
/*************************************************************************/
/* Prints the items in the queue. */
/*************************************************************************/
void queuePrint(CircularQueue *q) {
int i;
if (queueIsEmpty(q)) {
printf("Queue is empty.\n");
return;
}
printf("Items: ");
i = q->head;
do {
printf("%s ", q->store[i]);
} while (++i < q->tail);
printf("\n");
}