/** * array-queue.c * An implementation of linear structures using array-based queues. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include "collection.h" #include // For malloc #include // For strdup // +-----------+------------------------------------------------------ // | Constants | // +-----------+ #ifndef QUEUE_CAPACITY #define QUEUE_CAPACITY 100 #endif // QUEUE_CAPACITY // +-------+---------------------------------------------------------- // | Types | // +-------+ struct collection { char *contents[QUEUE_CAPACITY]; int size; int front; int back; }; // +-----------+------------------------------------------------------ // | Functions | // +-----------+ struct collection * new_collection (int recommended_capacity) { struct collection *result; result = malloc (sizeof (struct collection)); if (result == NULL) return NULL; result->size = 0; result->front = 0; result->back = 0; return result; } // new_collection void collection_free (struct collection *stuff) { int i; for (i = stuff->front; i != stuff->back; i = (i + 1) % QUEUE_CAPACITY) { free (stuff->contents[i]); stuff->contents[i] = NULL; } free (stuff); } // collection_free int collection_put (struct collection *stuff, char *str) { if (collection_is_full (stuff)) return 0; stuff->contents[stuff->back] = strdup (str); stuff->back = (stuff->back + 1) % QUEUE_CAPACITY; ++(stuff->size); return 1; } // collection_put char * collection_get (struct collection *stuff) { if (collection_is_empty (stuff)) return NULL; char *result = stuff->contents[stuff->front]; stuff->contents[stuff->front] = NULL; // Don't keep pointers around stuff->front = (stuff->front + 1) % QUEUE_CAPACITY; --(stuff->size); return result; } // collection_get char * collection_peek (struct collection *stuff) { if (collection_is_empty (stuff)) return NULL; return stuff->contents[stuff->front]; } // collection_peek int collection_size (struct collection *stuff) { return stuff->size; } // collection_size int collection_is_empty (struct collection *stuff) { return (stuff->size == 0); } // collection_is_empty int collection_is_full (struct collection *stuff) { return (stuff->size == QUEUE_CAPACITY); } // collection_is_full