Last active
July 18, 2021 16:09
-
-
Save Keyaku/a4720ca52c6c9e13a7c16c006f2de0c2 to your computer and use it in GitHub Desktop.
A simple but effective Queue structure in C for School projects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <string.h> | |
#include "queue.h" | |
Queue *queue_new(Queue *q, size_t size, bool (*equals)(const void*, const void*)) | |
{ | |
if (size <= 0) return NULL; | |
q->data = malloc((size+1)* sizeof(*q->data), false); | |
q->front = q->rear = 0; | |
q->equals = equals; | |
return q; | |
} | |
void queue_destroy(Queue *q) | |
{ | |
if (q == NULL) return; | |
free(q->data); q->data = NULL; | |
} | |
bool queue_contains(Queue *q, Object key) | |
{ | |
if (q->equals == NULL) { | |
fprintf(stderr, "%s: equals callback undefined\n", __func__); | |
return false; | |
} | |
for (int idx = q->front; idx < q->rear; idx++) { | |
if (q->equals(q->data[idx], key)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
void queue_push(Queue *q, Object key) | |
{ | |
if (queue_contains(q, key)) { return; } | |
q->data[q->rear++] = key; | |
} | |
Object queue_pop(Queue *q) | |
{ | |
return q->data[q->front++]; | |
} | |
int queue_size(Queue *q) { return q->rear - q->front; } | |
bool queue_is_empty(Queue *q) { return q->front == q->rear; } | |
void queue_reset(Queue *q) | |
{ | |
q->front = q->rear = 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef _QUEUE_H_ | |
#define _QUEUE_H_ | |
typedef unsigned char bool; | |
#define true 1 | |
#define false 0 | |
typedef void* Object; | |
typedef struct _queue { | |
int front, rear; | |
void* *data; /* data[idx] = obj */ | |
bool (*equals)(const void*, const void*); | |
} Queue; | |
Queue *queue_new(Queue *q, size_t size, bool (*equals)(const void*, const void*)); | |
void queue_destroy(Queue *q); | |
bool queue_contains(Queue *q, Object key); | |
void queue_push(Queue *q, Object key); | |
Object queue_pop(Queue *q); | |
int queue_size(Queue *q); | |
bool queue_is_empty(Queue *q); | |
void queue_reset(Queue *q); | |
void queue_sort(Queue *q); | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment