본문 바로가기

C/코드 리뷰

큐 구현 (원형 큐)

반응형
SMALL

큐를 구현해봅시다.

 

구현하려는 큐는 원형 큐입니다.

 

자세한 건 코드로 살펴보도록 하겠습니다.

 

main 함수는 stack과 유사합니다.

#include <stdio.h>

#define MAX_N 100

int front; // 시작을 가리킵니다.
int rear; // 끝을 가리킵니다.
int queue[MAX_N]; // 큐 최대 크기 100

void queueInit(void) {
	front = 0;
	rear = 0;
}

int queueIsEmpty(void) {
	return (front == rear); // front와 rear가 같은 위치를 가르키고 있으면 큐가 비어있는 상태입니다.
}

int queueIsFull(void) {
	return ((rear + 1) % MAX_N == front); // rear가 가르키는 다음 위치에 front가 있으면 큐가 꽉 찬 상황입니다.
}

int queueEnqueue(int value) {
	if (queueIsFull()) {
		printf("queue is full");
		return 0;
	}
	queue[rear] = value;
	rear++;
	if (rear == MAX_N) { // rear가 큐의 끝까지 갔다면 다시 0으로 돌아옵니다.
		rear = 0;
	}
	return 1;
}

int queueDequeue(int* value) {
	if (queueIsEmpty()) {
		printf("queue is empty");
		return 0;
	}
	*value = queue[front];
	front++;
	if (front == MAX_N) { // front가 큐의 끝까지 갔다면 다시 0으로 돌아옵니다.
		front = 0;
	}
	return 1;
}

int main(void) {
	int T, N;

	scanf("%d", &T);

	for (int t = 1; t <= T; ++t) {
		scanf("%d", &N);

		queueInit();
		
		for (int i = 0; i < N; ++i) { // 큐에 집어넣습니다.
			int value;
			scanf("%d", &value);
			queueEnqueue(value);
		}

		printf("#%d ", t);

		while (!queueIsEmpty()) { // 큐에서 뺍니다.
			int value;
			if (queueDequeue(&value) == 1) {
				printf("%d ", value);
			}
		}
	}
	return 0;
}
반응형
LIST

'C > 코드 리뷰' 카테고리의 다른 글

C언어 순열과 조합  (0) 2020.01.11
우선순위 큐 구현  (0) 2019.08.15
스택 구현  (0) 2019.08.15
Linked List 구현하기 (1)  (0) 2019.06.23
이진 탐색(Binary Search) 알고리즘과 시간 복잡도 분석  (0) 2019.06.21