fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define QUEUE_SIZE 100
  4.  
  5. typedef int element;
  6. element queue[QUEUE_SIZE]; // 큐 배열 선언
  7. int front = 0, rear = 0; // front와 rear 초기화
  8.  
  9. int isEmpty() {
  10. return front == rear;
  11. }
  12.  
  13. int isFull() {
  14. return (rear + 1) % QUEUE_SIZE == front;
  15. }
  16.  
  17. void enqueue(element item) {
  18. if (isFull()) {
  19. printf("\nQueue is Full!\n");
  20. return;
  21. }
  22. rear = (rear + 1) % QUEUE_SIZE;
  23. queue[rear] = item;
  24. }
  25.  
  26. element dequeue() {
  27. if (isEmpty()) {
  28. printf("\nQueue is Empty!\n");
  29. return -1;
  30. }
  31. front = (front + 1) % QUEUE_SIZE;
  32. return queue[front];
  33. }
  34.  
  35. element peek() {
  36. if (isEmpty()) {
  37. printf("\nQueue is Empty!\n");
  38. exit(1);
  39. }
  40. return queue[(front + 1) % QUEUE_SIZE];
  41. }
  42.  
  43. void printQueue() {
  44. if (isEmpty()) {
  45. printf("\nQueue is Empty!\n");
  46. return;
  47. }
  48. printf("\nQueue [ ");
  49. int i = (front + 1) % QUEUE_SIZE;
  50. while (i != (rear + 1) % QUEUE_SIZE) {
  51. printf("%d ", queue[i]);
  52. i = (i + 1) % QUEUE_SIZE;
  53. }
  54. printf("]\n");
  55. }
  56.  
  57. int main(void) {
  58. element item;
  59.  
  60. printf("순차 큐 연산\n");
  61. printQueue();
  62.  
  63. enqueue(10); printQueue();
  64. enqueue(20); printQueue();
  65. enqueue(30); printQueue();
  66.  
  67. item = peek();
  68. printf("peek => %d\n", item);
  69.  
  70. item = dequeue();
  71. printQueue();
  72. printf("\tdequeue => %d\n", item);
  73.  
  74. item = dequeue();
  75. printQueue();
  76. printf("\tdequeue => %d\n", item);
  77.  
  78. item = dequeue();
  79. printQueue();
  80. printf("\tdequeue => %d\n", item);
  81.  
  82. return 0;
  83. }
  84.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
순차 큐 연산

Queue is Empty!

Queue [ 10 ]

Queue [ 10 20 ]

Queue [ 10 20 30 ]
peek => 10

Queue [ 20 30 ]
	dequeue => 10

Queue [ 30 ]
	dequeue => 20

Queue is Empty!
	dequeue => 30