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 _Queue
- {
- int front;
- int rear;
- element arr[MAX_QUEUE_SIZE];
- } Queue;
- // 큐를 초기화하는 함수
- void Queue_init(Queue* q)
- {
- q->front = q->rear = -1;
- }
- // 큐가 꽉 찼다면 1, 아니면 0
- int Queue_isFull(Queue* q)
- {
- return q->rear == MAX_QUEUE_SIZE - 1;
- }
- // 큐가 비었다면 1, 아니면 0
- int Queue_isEmpty(Queue* q)
- {
- return q->front == q->rear;
- }
- // 큐에 삽입
- void Queue_enqueue(Queue* q, element e)
- {
- if (Queue_isFull(q))
- {
- fprintf(stderr, "Queue is full!\n");
- exit(1);
- }
- q->arr[++q->rear] = e; // rear를 증가한 다음 그 자리에 삽입
- }
- // 큐에서 제거
- element Queue_dequeue(Queue* q)
- {
- if (Queue_isEmpty(q))
- {
- fprintf(stderr, "Queue is empty!\n");
- exit(1);
- }
- // front를 하나 증가시키고, 그 자리의 요소를 리턴
- return q->arr[++q->front];
- }
- // 큐 출력
- void Queue_print(Queue* q)
- {
- if (Queue_isEmpty(q))
- {
- printf("Empty Queue!\n");
- return;
- }
- for (int i = 0; i < MAX_QUEUE_SIZE; ++i)
- {
- // front + 1 ~ rear 인덱스를 출력
- if (i > q->front && i <= q->rear)
- printf("| %2d ", q->arr[i]);
- else
- printf("| ");
- }
- printf("\n\n");
- }
- int main(int argc, char* argv[])
- {
- Queue q;
- Queue_init(&q);
- Queue_print(&q);
- Queue_enqueue(&q, 10);
- Queue_enqueue(&q, 20);
- Queue_enqueue(&q, 30);
- Queue_enqueue(&q, 40);
- Queue_print(&q);
- printf("dequeue : %2d\n", Queue_dequeue(&q));
- printf("dequeue : %2d\n", Queue_dequeue(&q));
- printf("dequeue : %2d\n", Queue_dequeue(&q));
- Queue_print(&q);
- Queue_enqueue(&q, 50);
- Queue_enqueue(&q, 60);
- Queue_enqueue(&q, 70);
- Queue_print(&q);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement