From 0cf053589ed6e6f07c7e15b9123fa62f245c5a24 Mon Sep 17 00:00:00 2001 From: tommi27 Date: Sun, 1 Sep 2019 14:52:45 +0200 Subject: [PATCH] created queue in c and python --- collections/queue.c | 48 ++++++++++++++++++++++++++++++++++++++++++++ collections/queue.py | 20 ++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 collections/queue.c create mode 100644 collections/queue.py diff --git a/collections/queue.c b/collections/queue.c new file mode 100644 index 0000000..989bccc --- /dev/null +++ b/collections/queue.c @@ -0,0 +1,48 @@ +#include +#include +#include + +// 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; + } +} diff --git a/collections/queue.py b/collections/queue.py new file mode 100644 index 0000000..c7eb578 --- /dev/null +++ b/collections/queue.py @@ -0,0 +1,20 @@ +class Queue: + def __init__(self, length): + self.length = length + self.arr = [None]*length + self.start = 0 + self.size = 0 + +def enqueue(Q, x): + if Q.size == Q.length: + return "You broke it, congratulations!" + Q.arr[Q.start + Q.size] = x + Q.size = Q.size + 1 + +def dequeue(Q): + if Q.size == 0: + return "You broke it, congratulations!" + temp = Q.arr[Q.start] + Q.start = (Q.start + 1) % Q.length + Q.size = Q.size - 1 + return temp