This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
sys_prog/collections/queue.c

49 lines
1 KiB
C
Raw Normal View History

2019-09-01 12:52:45 +00:00
#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;
}
}