Created
February 15, 2024 10:36
-
-
Save jangsoopark/f129424c850213dcbcf67e2bd809fbc8 to your computer and use it in GitHub Desktop.
This file contains 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 <stdbool.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <math.h> | |
typedef struct Queue | |
{ | |
int* buffer; | |
int front; | |
int back; | |
int count; | |
int size; | |
} Queue; | |
int size(Queue* q) | |
{ | |
return q->count; | |
} | |
bool empty(Queue* q) | |
{ | |
return size(q) == 0; | |
} | |
bool full(Queue* q) | |
{ | |
return size(q) == q->size; | |
} | |
bool push(Queue* q, int v) | |
{ | |
if (full(q)) | |
return false; | |
q->buffer[q->back] = v; | |
q->back = (q->back + 1) % q->size; | |
q->count++; | |
return true; | |
} | |
int pop(Queue* q) | |
{ | |
if (empty(q)) | |
return -1; | |
q->count--; | |
q->front = (q->front + 1) % q->size; | |
return q->buffer[ (q->front - 1 + q->size) % q->size ]; | |
} | |
int front(Queue* q) | |
{ | |
if (empty(q)) | |
return -1; | |
return q->buffer[q->front]; | |
} | |
int back(Queue* q) | |
{ | |
if (empty(q)) | |
return -1; | |
return q->buffer[ (q->back - 1 + q->size) % q->size ]; | |
} | |
int main(void) | |
{ | |
Queue q = {NULL, 0, 0, 0, 0}; | |
int N = 5; | |
int i; | |
q.buffer = (int*)malloc(sizeof(int) * N); | |
q.size = N; | |
for(i = 0; i < 10; i++) | |
{ | |
push(&q, i); | |
printf("%d %d %d | %d %d %d\n", i, q.front, q.back, front(&q), back(&q), size(&q)); | |
} | |
for(i = 0; i < 20; i++) | |
{ | |
pop(&q); | |
printf("%d %d %d | %d %d %d\n", i, q.front, q.back, front(&q), back(&q), size(&q)); | |
push(&q, 10 + i); | |
} | |
free(q.buffer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment