#include #define QUEUE_SIZE 10 /* * Simple queue algorithm implementation * * tail will always point to the next available slot */ struct queue { int data[QUEUE_SIZE]; int head; int tail; }; int queue_empty(struct queue *Q) { return Q->head == Q->tail; } /* * Queue is full when: * tail + 1 == HEAD or * TAIL == QUEUE_SIZE - 1 and HEAD == 0 */ int queue_full(struct queue *Q) { if (((Q->tail + 1) == Q->head) || ((Q->tail == (QUEUE_SIZE - 1)) && (Q->head == 0))) return 1; else return 0; } int queue_push(struct queue *Q, int value) { if (queue_full(Q)) { printf("Queue is full, avoiding overflow\n"); return 0; } Q->data[Q->tail] = value; if (Q->tail == (QUEUE_SIZE - 1)) Q->tail = 0; else Q->tail++; return value; } /* FIXME: function return 0 in case of failure, should return something * else, once 0 is a valid value to the queue */ int queue_pop(struct queue *Q) { int value = 0; if (queue_empty(Q)) { printf("Queue is empty, avoiding underflow\n"); return value; } value = Q->data[Q->head]; if (Q->head == (QUEUE_SIZE - 1)) Q->head = 0; else Q->head++; return value; } void print_queue(struct queue *Q) { int i = Q->head; int pos = 1; if (queue_empty(Q)) { printf("Nothing to print, queue is empty\n"); return; } printf(" Pos | Tail \n"); for (;;) { printf(" %d | %d \n", pos, Q->data[i]); if (i == (QUEUE_SIZE - 1)) i = 0; else i++; pos++; if (i == Q->tail) break; } } void debug_queue(struct queue *Q) { int i; for (i = 0; i < QUEUE_SIZE; i++) { printf("| %d | ", Q->data[i]); if (i == Q->head) printf("<-- HEAD "); if (i == Q->tail) printf("<-- TAIL"); printf("\n"); } } int main(void) { struct queue my_queue; int i, val; char cmd; /* Init queue */ my_queue.head = 0; my_queue.tail = 0; for (i = 0; i < QUEUE_SIZE; i++) my_queue.data[i] = 0; while (1) { printf("Select an option: "); scanf(" %c", &cmd); switch (cmd) { case 'a': printf("Value to add: "); scanf(" %d", &val); queue_push(&my_queue, val); break; case 'p': queue_pop(&my_queue); break; case 'd': debug_queue(&my_queue); break; case 'l': print_queue(&my_queue); break; default: printf("Invalid option\n"); printf("a = add, p = pop, d = debug, l = print\n"); } } return 0; }