Created
August 12, 2020 17:47
-
-
Save cs-fedy/86563b79df124df3f9aee5193003480e to your computer and use it in GitHub Desktop.
queue implementation in C.
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 <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
struct Queue { | |
int * keys; | |
int head; | |
int tail; | |
int max_size; | |
}; | |
typedef struct Queue Queue; | |
Queue * create_queue(int); | |
unsigned is_empty(Queue); | |
int get_head(Queue); | |
void enqueue(Queue *, int); | |
void dequeue(Queue *); | |
Queue * create_queue(int max_size) { | |
Queue * qu = malloc(sizeof(Queue)); | |
qu -> keys = malloc(max_size * sizeof(int)); | |
qu -> head = 0; | |
qu -> tail = 0; | |
qu -> max_size = max_size; | |
return qu; | |
} | |
unsigned is_empty(Queue qu) { | |
return qu.head == qu.tail; | |
} | |
int get_head(Queue qu) { | |
assert(!is_empty(qu)); | |
int index = qu.head + 1; | |
if (index > qu.max_size - 1) | |
index = 0; | |
return qu.keys[qu.head]; | |
} | |
void enqueue(Queue * qu, int key) { | |
qu -> tail++; | |
if (qu -> tail > qu -> max_size - 1) | |
qu -> tail = 0; | |
assert(!is_empty(*qu)); | |
qu -> keys[qu -> tail] = key; | |
} | |
void dequeue(Queue * qu) { | |
assert(!is_empty(*qu)); | |
qu -> head++; | |
if (qu -> head > qu -> max_size - 1) | |
qu -> head = 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment