Data Structure – Queue (c)

자료구조 큐 c언어 소스

#include <stdio.h>
#define MAX_QUEUE_SIZE 5
typedef int element;
typedef struct {
	element data[MAX_QUEUE_SIZE];
	int front, rear;
}QueueType;
typedef QueueType* QueueType_ptr;

void init(QueueType_ptr q) {
	q->front = 0;
	q->rear = 0;
}

int is_empty(QueueType q) {
	if (q.front == q.rear)
		return 1;
	else
		return 0;
};

int is_full(QueueType q) {
	if ((q.rear + 1) % MAX_QUEUE_SIZE == q.front)
		return 1;
	else
		return 0;
}

void enqueue(QueueType_ptr q, int item) {
	if (!is_full(*q)) {
		q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
		q->data[q->rear] = item;
	}
	else
		printf("큐가 꽉 찼습니다");
}

int dequeue(QueueType_ptr q) {
	if (!is_empty(*q)) {
		q->front = (q->front + 1) % MAX_QUEUE_SIZE;
		return q->data[q->front];
	}
	else
		printf("큐가 비어 있습니다");
}

int peek(QueueType q) {
	if (!is_empty(q))
		return q.data[(q.front + 1) % MAX_QUEUE_SIZE];
	else
		printf("큐가 비어 있습니다");
}

int main() {
	QueueType q;
	init(&q);

	enqueue(&q, 10); // 10
	enqueue(&q, 11); // 10 11
	enqueue(&q, 12); // 10 11 12
	printf("[%d]\n", dequeue(&q)); // 10 <- 10 11 12
	printf("[%d]", peek(q)); // 11 12
}

Leave a Reply

Your email address will not be published. Required fields are marked *