created queue in c and python
This commit is contained in:
parent
8660ff8bad
commit
0cf053589e
2 changed files with 68 additions and 0 deletions
48
collections/queue.c
Normal file
48
collections/queue.c
Normal file
|
@ -0,0 +1,48 @@
|
|||
#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;
|
||||
}
|
||||
}
|
20
collections/queue.py
Normal file
20
collections/queue.py
Normal file
|
@ -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
|
Reference in a new issue