Last active
February 4, 2025 07:10
-
-
Save BurntNail/ce711afd8c7f4e6beb372db33fe828d2 to your computer and use it in GitHub Desktop.
Very basic double-ended queue in C99
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
| // | |
| // Created by jack on 03/02/25. | |
| // | |
| #include <stdlib.h> | |
| #include <string.h> | |
| typedef struct Queue { | |
| int* allocation_start; | |
| int* start; | |
| int* end; | |
| int capacity; | |
| } Queue; | |
| Queue Queue_createQueue(int capacity); | |
| void Queue_destroyQueue(const Queue* queue); | |
| void Queue_push(Queue* queue, int value); | |
| bool Queue_popBack(Queue* queue, int* output); | |
| bool Queue_popFront(Queue* queue, int* output); | |
| Queue Queue_createQueue(const int capacity) { | |
| int* start = (int*)malloc(sizeof(int) * capacity); | |
| Queue ret = { | |
| .allocation_start = start, | |
| .start = start, | |
| .end = start, | |
| .capacity = capacity, | |
| }; | |
| return ret; | |
| } | |
| void Queue_destroyQueue(const Queue* queue) { | |
| free(queue->allocation_start); | |
| } | |
| void Queue_push(Queue* queue, const int value) { | |
| if (queue->end == (queue->allocation_start + queue->capacity)) { | |
| int currentLength = queue->end - queue->start; | |
| int newAllocSize = queue->capacity * 2; | |
| int* newAllocation = (int*)malloc(sizeof(int) * newAllocSize); | |
| memcpy(newAllocation, queue->start, sizeof(int) * currentLength); | |
| free(queue->allocation_start); | |
| queue->allocation_start = newAllocation; | |
| queue->start = queue->allocation_start; | |
| queue->end = queue->allocation_start + currentLength; | |
| queue->capacity *= newAllocSize; | |
| } | |
| *queue->end = value; | |
| queue->end++; | |
| } | |
| bool Queue_popBack(Queue *queue, int *output) { | |
| if (queue->end == queue->allocation_start + queue->capacity || queue->end == queue->start) { | |
| return false; | |
| } | |
| queue->end--; | |
| *output = *queue->end; | |
| return true; | |
| } | |
| bool Queue_popFront(Queue *queue, int *output) { | |
| if (queue->end == queue->allocation_start + queue->capacity || queue->start == queue->end) { | |
| return false; | |
| } | |
| *output = *queue->start; | |
| queue->start++; | |
| return true; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment