one-file-projects/queue.c

68 lines
1.2 KiB
C
Raw Normal View History

2016-02-10 18:07:03 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct {
int* elements;
int head;
int tail;
int size;
} queue;
queue* qcreate();
void qput(queue *q, int element);
int qget(queue *q);
int qempty(queue *q);
int qfull(queue *q);
void qclear(queue* q);
queue* qcreate(int size) {
queue* q = malloc(sizeof(queue));
q->elements = malloc(sizeof(int) * size);
q->size = size;
qclear(q);
return q;
}
void qput(queue* q, int element) {
assert(q->tail != -1);
q->elements[q->tail] = element;
q->tail = (q->tail + 1) % q->size;
if(q->head == q->tail) q->tail = -1;
}
int qget(queue* q) {
assert(q->tail != q->head);
if(q->tail == -1) q->tail = q->head;
int element = q->elements[q->head];
q->head = (q->head + 1) % q->size;
return element;
}
int qempty(queue* q) {
return (q->head == q->tail);
}
int qfull(queue* q) {
return (q->tail == -1);
}
void qclear(queue *q) {
q->head = 0;
q->tail = 0;
}
void qdestroy(queue *q) {
free(q->elements);
free(q);
}
int main( int argc, char *argv[] ) {
queue* q = qcreate(300);
int i = 0;
while(!qfull(q)) qput(q,i++);
while(!qempty(q)) printf("%d\n",qget(q));
return 0;
}