Skip to content

Instantly share code, notes, and snippets.

@rk76feWF
Created March 7, 2023 14:20
Show Gist options
  • Save rk76feWF/69df27bd0bce3b60cfce69e345aea15b to your computer and use it in GitHub Desktop.
Save rk76feWF/69df27bd0bce3b60cfce69e345aea15b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include "queue.h"
int main(void)
{
QUEUE_T *q = create_queue(4);
q->push(q, 'a');
q->push(q, 'b');
q->push(q, 'c');
q->push(q, 'd');
printf("%c: 残り%d個\n", q->pop(q), q->size(q));
printf("%c: 残り%d個\n", q->pop(q), q->size(q));
q->clear(q);
q->push(q, 'e');
q->push(q, 'f');
printf("%c: 残り%d個\n", q->pop(q), q->size(q));
printf("%c: 残り%d個\n", q->pop(q), q->size(q));
printf("%c: 残り%d個\n", q->pop(q), q->size(q));
free_queue(q);
return 0;
}
#include <stdio.h>
#include <stdlib.h> // malloc, free
#include "queue.h"
void push(QUEUE_T *q, data_t x)
{
if ((q->rear + 1) % q->max_size == q->front)
{
printf("Queue is full\n");
return;
}
q->rear = (q->rear + 1) % q->max_size;
q->data[q->rear] = x;
}
data_t pop(QUEUE_T *q)
{
if (q->front == q->rear)
{
printf("Queue is empty\n");
return -1;
}
q->front = (q->front + 1) % q->max_size;
return q->data[q->front];
}
void clear(QUEUE_T *q)
{
q->front = 0;
q->rear = 0;
return;
}
int size(QUEUE_T *q)
{
if ((q->rear - q->front) >= 0)
return q->rear - q->front;
else
return q->max_size - (q->front - q->rear);
}
QUEUE_T *create_queue(int max_size)
{
QUEUE_T *q = (QUEUE_T *)malloc(sizeof(QUEUE_T));
if (q == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
q->data = (data_t *)malloc(sizeof(data_t) * max_size);
if (q->data == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
q->max_size = max_size;
q->front = 0;
q->rear = 0;
q->push = push;
q->pop = pop;
q->size = size;
q->clear = clear;
return q;
}
void free_queue(QUEUE_T *q)
{
free(q->data);
free(q);
}
typedef unsigned char data_t;
typedef struct queue
{
data_t *data; // データを格納する配列
int max_size; // キューのサイズ
int front; // 先頭要素のインデックス
int rear; // 末尾要素のインデックス
void (*push)(struct queue *, data_t); // キューにデータを追加する関数ポインタ
data_t (*pop)(struct queue *); // キューからデータを取り出す関数ポインタ
int (*size)(struct queue *); // キューのサイズを返す関数ポインタ
void (*clear)(struct queue *); // キューを初期化する関数ポインタ
void (*reserved)(struct queue *); // 予約領域
} QUEUE_T;
QUEUE_T *create_queue(int);
void free_queue(QUEUE_T *);
@rk76feWF
Copy link
Author

rk76feWF commented Mar 7, 2023

❯ gcc main.c queue.c && ./a.out
Queue is full
a: 残り2個
b: 残り1個
e: 残り1個
f: 残り0個
Queue is empty
: 残り0個

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment