49 lines
1 KiB
C
49 lines
1 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <stdbool.h>
|
||
|
|
||
|
// Type for queue, change to the desired type to be used in the queue
|
||
|
#define QUEUE_TYPE int
|
||
|
|
||
|
typedef struct queue {
|
||
|
size_t length;
|
||
|
QUEUE_TYPE* arr;
|
||
|
size_t start;
|
||
|
size_t size;
|
||
|
} queue_t;
|
||
|
|
||
|
queue_t queue_init(size_t length) {
|
||
|
queue_t self;
|
||
|
self.length = length;
|
||
|
self.arr = malloc(length * sizeof(QUEUE_TYPE))
|
||
|
self.start = 0;
|
||
|
self.size = 0;
|
||
|
return self;
|
||
|
}
|
||
|
|
||
|
bool enqueue(queue_t* self, QUEUE_TYPE element) {
|
||
|
if (self->size == self->length) {
|
||
|
return false;
|
||
|
}
|
||
|
self->arr[self->start + self->size] = element;
|
||
|
self->size++;
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
bool dequeue(queue_t* self, QUEUE_TYPE* destination) {
|
||
|
if (self->size == 0) {
|
||
|
return false;
|
||
|
}
|
||
|
*destination = self->arr[self->start];
|
||
|
self->start = (self->start + 1) % self->length;
|
||
|
self->size--;
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
void queue_destroy(queue_t* self) {
|
||
|
if (self->arr != NULL) {
|
||
|
free(self->arr);
|
||
|
self->arr = NULL;
|
||
|
}
|
||
|
}
|