Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define MAX_QUEUE_SIZE 10 // 큐 배열의 최대 크기
- typedef int element;
- // 원형 큐 구조체
- typedef struct _CircQueue
- {
- int front;
- int rear;
- element arr[MAX_QUEUE_SIZE];
- } CircQueue;
- // 큐 초기화
- void Queue_init(CircQueue* q)
- {
- q->front = q->rear = 0;
- }
- // 큐가 꽉 찼다면 1, 아니면 0
- int Queue_isFull(CircQueue* q)
- {
- return (q->rear + 1) % MAX_QUEUE_SIZE == q->front; // rear의 다음 칸이 front이면 포화상태
- }
- // 큐가 비었다면 1, 아니면 0
- int Queue_isEmpty(CircQueue* q)
- {
- return q->front == q->rear; // front와 rear가 같으면 빈 상태
- }
- // 큐에 요소 e를 삽입
- void Queue_enqueue(CircQueue* q, element e)
- {
- if (Queue_isFull(q))
- {
- fprintf(stderr, "Queue is full!\n");
- exit(1);
- }
- // 포화상태가 아니라면 rear를 하나 증가시키고, 나머지 연산을 한 다음 그 자리에 새 요소 삽입
- q->arr[ (++q->rear) % MAX_QUEUE_SIZE ] = e;
- }
- element Queue_dequeue(CircQueue* q)
- {
- if (Queue_isEmpty(q))
- {
- fprintf(stderr, "Queue is empty!\n");
- exit(1);
- }
- // 공백상태가 아니라면 front를 하나 증가시키고, 나머지 연산을 한 다음 그 자리에 있는 요소를 리턴
- return q->arr[ (++q->front) % MAX_QUEUE_SIZE ];
- }
- // 큐를 출력
- void Queue_print(CircQueue* q)
- {
- // 포스트 참고
- if (Queue_isEmpty(q))
- {
- printf("Queue is empty!\n");
- return;
- }
- int i;
- for (i = q->front + 1; i != q->rear; i = (i + 1) % MAX_QUEUE_SIZE)
- printf("%2d <- ", q->arr[i]);
- printf("%2d\n", q->arr[i]);
- }
- int main(int argc, char* argv[])
- {
- CircQueue q;
- Queue_init(&q);
- // 10, 20, 30, 40을 큐에 삽입
- Queue_enqueue(&q, 10);
- Queue_enqueue(&q, 20);
- Queue_enqueue(&q, 30);
- Queue_enqueue(&q, 40);
- Queue_print(&q);
- // 세번 큐에서 제거 : 10, 20, 30이 제거됨
- printf(">> dequeue : %2d\n", Queue_dequeue(&q));
- printf(">> dequeue : %2d\n", Queue_dequeue(&q));
- printf(">> dequeue : %2d\n\n", Queue_dequeue(&q));
- // 11, 22, 33을 큐에 삽입
- Queue_enqueue(&q, 11);
- Queue_enqueue(&q, 22);
- Queue_enqueue(&q, 33);
- Queue_print(&q);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement