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

65 lines
1.4 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 VECTOR_TYPE int
2019-09-01 12:52:45 +00:00
typedef struct queue {
size_t length;
VECTOR_TYPE* arr;
2019-09-01 12:52:45 +00:00
size_t start;
size_t size;
} vector_t;
2019-09-01 12:52:45 +00:00
inline static size_t queue_end(vector_t* self) {
return (self->start + self->size) % self->length;
}
vector_t vector_init(size_t length) {
vector_t self;
2019-09-01 12:52:45 +00:00
self.length = length;
self.arr = malloc(length * sizeof(VECTOR_TYPE));
2019-09-01 12:52:45 +00:00
self.start = 0;
self.size = 0;
return self;
}
bool vector_add(vector_t* self, VECTOR_TYPE element, bool to_end) {
2019-09-01 12:52:45 +00:00
if (self->size == self->length) {
return false;
}
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--;
}
}
2019-09-01 12:52:45 +00:00
self->size++;
return true;
}
bool vector_remove(vector_t* self, VECTOR_TYPE* destination, bool from_end) {
2019-09-01 12:52:45 +00:00
if (self->size == 0) {
return false;
}
*destination = self->arr[!from_end ? queue_end(self) : self->start];
if (from_end) {
self->start = (self->start + 1) % self->length;
}
2019-09-01 12:52:45 +00:00
self->size--;
return true;
}
void vector_destroy(vector_t* self) {
2019-09-01 12:52:45 +00:00
if (self->arr != NULL) {
free(self->arr);
self->arr = NULL;
}
}