queue is now a vector which works as a stack as well

This commit is contained in:
Tommaso Rodolfo Masera 2019-09-01 16:06:28 +02:00
parent 0cf053589e
commit 8cb1bee38c

View file

@ -3,44 +3,60 @@
#include <stdbool.h> #include <stdbool.h>
// Type for queue, change to the desired type to be used in the queue // Type for queue, change to the desired type to be used in the queue
#define QUEUE_TYPE int #define VECTOR_TYPE int
typedef struct queue { typedef struct queue {
size_t length; size_t length;
QUEUE_TYPE* arr; VECTOR_TYPE* arr;
size_t start; size_t start;
size_t size; size_t size;
} queue_t; } vector_t;
queue_t queue_init(size_t length) { inline static size_t queue_end(vector_t* self) {
queue_t self; return (self->start + self->size) % self->length;
}
vector_t vector_init(size_t length) {
vector_t self;
self.length = length; self.length = length;
self.arr = malloc(length * sizeof(QUEUE_TYPE)) self.arr = malloc(length * sizeof(VECTOR_TYPE));
self.start = 0; self.start = 0;
self.size = 0; self.size = 0;
return self; return self;
} }
bool enqueue(queue_t* self, QUEUE_TYPE element) { bool vector_add(vector_t* self, VECTOR_TYPE element, bool to_end) {
if (self->size == self->length) { if (self->size == self->length) {
return false; return false;
} }
self->arr[self->start + self->size] = element; if (to_end) {
self->arr[queue_end(self)] = element;
} else {
if (self->size == 0) {
self->arr[self->start] = element;
} else {
self->arr[self->start - 1] = element;
self->start--;
}
}
self->size++; self->size++;
return true; return true;
} }
bool dequeue(queue_t* self, QUEUE_TYPE* destination) { bool vector_remove(vector_t* self, VECTOR_TYPE* destination, bool from_end) {
if (self->size == 0) { if (self->size == 0) {
return false; return false;
} }
*destination = self->arr[self->start];
self->start = (self->start + 1) % self->length; *destination = self->arr[!from_end ? queue_end(self) : self->start];
if (from_end) {
self->start = (self->start + 1) % self->length;
}
self->size--; self->size--;
return true; return true;
} }
void queue_destroy(queue_t* self) { void vector_destroy(vector_t* self) {
if (self->arr != NULL) { if (self->arr != NULL) {
free(self->arr); free(self->arr);
self->arr = NULL; self->arr = NULL;