fork download
  1. #include <stdio.h>
  2.  
  3. #define SIZE 5
  4. int queue[SIZE];
  5. int head, tail;
  6.  
  7. void enqueue(int value);
  8. int dequeue(void);
  9.  
  10. int main(void)
  11. {
  12. head = tail = 0;
  13. int resp, data, i;
  14.  
  15. while(1){
  16. printf("1:enqueue 2:dequeue 0:end > ");
  17. scanf("%d", &resp);
  18.  
  19. if(resp == 0) break;
  20.  
  21. switch (resp){
  22. case 1:
  23. printf("enqueue(1): 'value' > ");
  24. scanf("%d", &data);
  25. enqueue(data);
  26. break;
  27. case 2:
  28. dequeue();
  29. break;
  30. }
  31.  
  32. printf("head:%d, tail:%d\n", head, tail); // headとtailの現在位置を表示
  33.  
  34. printf("queue:");
  35. if (head != tail) {
  36. i = head;
  37. while(i != tail){
  38. printf("queue[%d]=%d, ", i, queue[i]);
  39. i = (i + 1) % SIZE;
  40. }
  41. }
  42. printf("\n");
  43. }
  44.  
  45. return 0;
  46. }
  47.  
  48. void enqueue(int value)
  49. {
  50. if (head == (tail+1)%SIZE) {
  51. printf("キューは満杯で入りませんでした\n");
  52. } else {
  53. queue[tail] = value;
  54. tail = (tail + 1) % SIZE;
  55. }
  56. }
  57.  
  58. int dequeue(void)
  59. {
  60. int value;
  61. if (head == tail) {
  62. printf("キューは空で取り出せませんでした\n");
  63. return 0; // またはエラー値
  64. } else {
  65. value = queue[head];
  66. head = (head + 1) % SIZE;
  67. return value;
  68. }
  69. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
1:enqueue 2:dequeue 0:end >