Advertisement
nyhryan

Untitled

Jul 12th, 2023
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.94 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MAX_QUEUE_SIZE 10
  4.  
  5. typedef int element;
  6. typedef struct _Queue
  7. {
  8.     int front;
  9.     int rear;
  10.     element arr[MAX_QUEUE_SIZE];
  11. } Queue;
  12.  
  13. // 큐를 초기화하는 함수
  14. void Queue_init(Queue* q)
  15. {
  16.     q->front = q->rear = -1;
  17. }
  18.  
  19. // 큐가 꽉 찼다면 1, 아니면 0
  20. int Queue_isFull(Queue* q)
  21. {
  22.     return q->rear == MAX_QUEUE_SIZE - 1;
  23. }
  24.  
  25. // 큐가 비었다면 1, 아니면 0
  26. int Queue_isEmpty(Queue* q)
  27. {
  28.     return q->front == q->rear;
  29. }
  30.  
  31. // 큐에 삽입
  32. void Queue_enqueue(Queue* q, element e)
  33. {
  34.     if (Queue_isFull(q))
  35.     {
  36.         fprintf(stderr, "Queue is full!\n");
  37.         exit(1);
  38.     }
  39.     q->arr[++q->rear] = e; // rear를 증가한 다음 그 자리에 삽입
  40. }
  41.  
  42. // 큐에서 제거
  43. element Queue_dequeue(Queue* q)
  44. {
  45.     if (Queue_isEmpty(q))
  46.     {
  47.         fprintf(stderr, "Queue is empty!\n");
  48.         exit(1);
  49.     }
  50.     // front를 하나 증가시키고, 그 자리의 요소를 리턴
  51.     return q->arr[++q->front];
  52. }
  53.  
  54. // 큐 출력
  55. void Queue_print(Queue* q)
  56. {
  57.     if (Queue_isEmpty(q))
  58.     {
  59.         printf("Empty Queue!\n");
  60.         return;
  61.     }
  62.  
  63.     for (int i = 0; i < MAX_QUEUE_SIZE; ++i)
  64.     {
  65.         // front + 1 ~ rear 인덱스를 출력
  66.         if (i > q->front && i <= q->rear)
  67.             printf("| %2d ", q->arr[i]);
  68.         else
  69.             printf("|    ");
  70.     }
  71.  
  72.     printf("\n\n");
  73. }
  74.  
  75. int main(int argc, char* argv[])
  76. {
  77.     Queue q;
  78.  
  79.     Queue_init(&q);
  80.     Queue_print(&q);
  81.  
  82.     Queue_enqueue(&q, 10);
  83.     Queue_enqueue(&q, 20);
  84.     Queue_enqueue(&q, 30);
  85.     Queue_enqueue(&q, 40);
  86.     Queue_print(&q);
  87.  
  88.     printf("dequeue : %2d\n", Queue_dequeue(&q));
  89.     printf("dequeue : %2d\n", Queue_dequeue(&q));
  90.     printf("dequeue : %2d\n", Queue_dequeue(&q));
  91.     Queue_print(&q);
  92.  
  93.     Queue_enqueue(&q, 50);
  94.     Queue_enqueue(&q, 60);
  95.     Queue_enqueue(&q, 70);
  96.     Queue_print(&q);
  97.  
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement