Advertisement
nyhryan

Untitled

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