fork download
  1. #include <stdio.h>
  2.  
  3. #define SIZE 5
  4. int queue[SIZE];
  5. int head, tail;
  6.  
  7.  
  8. void enqueue(int value);
  9. int dequeue(void);
  10. int isFull(void);
  11. int isEmpty(void);
  12. void display(void);
  13. void initialize(void);
  14.  
  15. int main(void){
  16. head = tail = 0;
  17. int resp, data;
  18.  
  19. while(1){
  20. printf("\n1: enqueue 2: dequeue 3: initialize 0: end → ");
  21. scanf("%d", &resp);
  22.  
  23. if(resp == 0) break;
  24.  
  25. switch(resp){
  26. case 1:
  27. printf("enqueue → ");
  28. scanf("%d", &data);
  29. enqueue(data);
  30. break;
  31. case 2:
  32. dequeue();
  33. break;
  34. case 3:
  35. initialize();
  36. break;
  37. default:
  38. printf("無効な入力です。\n");
  39. break;
  40. }
  41.  
  42. printf("head=%d, tail=%d\n", head, tail);
  43. display();
  44. }
  45.  
  46. return 0;
  47. }
  48.  
  49. int isFull(void){
  50. return ((tail + 1) % SIZE == head);
  51. }
  52.  
  53.  
  54. int isEmpty(void){
  55. return (head == tail);
  56. }
  57.  
  58.  
  59. void enqueue(int value){
  60. if(isFull()){
  61. printf(" キューが満杯です!\n");
  62. return;
  63. }
  64. queue[tail] = value;
  65. tail = (tail + 1) % SIZE;
  66. printf("%d を追加しました。\n", value);
  67. }
  68.  
  69.  
  70. int dequeue(void){
  71. if(isEmpty()){
  72. printf("キューが空です!\n");
  73. return -1;
  74. }
  75.  
  76. int value = queue[head];
  77. queue[head] = 0;
  78. head = (head + 1) % SIZE;
  79. printf("%d を取り出しました。\n", value);
  80. return value;
  81. }
  82.  
  83.  
  84. void display(void){
  85. if(isEmpty()){
  86. printf("(現在キューは空です)\n");
  87. return;
  88. }
  89.  
  90. printf("キューの中身:\n");
  91. int i = head;
  92. while(i != tail){
  93. printf(" queue[%d] = %d\n", i, queue[i]);
  94. i = (i + 1) % SIZE;
  95. }
  96. }
  97.  
  98.  
  99. void initialize(void){
  100. head = tail = 0;
  101. for(int i = 0; i < SIZE; i++){
  102. queue[i] = 0;
  103. }
  104. printf("キューを初期化しました。\n");
  105. }
  106.  
Success #stdin #stdout 0.01s 5324KB
stdin
1
10
1
20
2
3
1
99
0
stdout
1: enqueue  2: dequeue  3: initialize  0: end → enqueue → 10 を追加しました。
head=0, tail=1
キューの中身:
 queue[0] = 10

1: enqueue  2: dequeue  3: initialize  0: end → enqueue → 20 を追加しました。
head=0, tail=2
キューの中身:
 queue[0] = 10
 queue[1] = 20

1: enqueue  2: dequeue  3: initialize  0: end → 10 を取り出しました。
head=1, tail=2
キューの中身:
 queue[1] = 20

1: enqueue  2: dequeue  3: initialize  0: end → キューを初期化しました。
head=0, tail=0
(現在キューは空です)

1: enqueue  2: dequeue  3: initialize  0: end → enqueue → 99 を追加しました。
head=0, tail=1
キューの中身:
 queue[0] = 99

1: enqueue  2: dequeue  3: initialize  0: end →