/* -- l_queue.c -- Tony Givargis Linked list Queue implementation for medium to large memory models. */ #include #include "l_queue.h" /*---------------------------------------------------------------------------*/ /* EL_QueueCreate Creates an empty queue and returns an EL_Queue* ADT to caller. This ADT is passed to subsequent queue functions as the identifier (handle) of this particular queue. Returns EL_Queue* on success, NULL otherwise. --> O(1) */ EL_Queue* EL_QueueCreate(void) { EL_Queue* q = malloc(sizeof(EL_Queue)); if( q != NULL ) { q->head = NULL; q->tail = NULL; q->size = 0; } return q; } /*---------------------------------------------------------------------------*/ /* EL_QueueDestroy Destroys queue (q). --> O(n) */ void EL_QueueDestroy(EL_Queue* q) { while( q->head != NULL ) { q->tail = q->head; q->head = q->head->link; free(q->tail); } free(q); } /*---------------------------------------------------------------------------*/ /* EL_QueuePush Pushes data (element) onto the queue (q). Retruns data element on success, NULL otherwise. --> O(1) */ void* EL_QueuePush(EL_Queue* q, void* element) { EL_QueueNode* n = malloc(sizeof(EL_QueueNode)); if( n != NULL ) { n->element = element; n->link = NULL; q->size++; if( q->tail != NULL ) { /* queue is not empty */ q->tail->link = n; } if( q->head == NULL ) { /* queue is empty */ q->head = n; } q->tail = n; } return n; } /*---------------------------------------------------------------------------*/ /* EL_QueuePop Pops data element from the queue (q). Returns data element on success, NULL otherwise. --> O(1) */ void* EL_QueuePop(EL_Queue* q) { void* element = NULL; EL_QueueNode* n = q->head; if( n != NULL ) { q->size--; q->head = n->link; element = n->element; if( q->head == NULL ) { q->tail = NULL; } free(n); } return element; }