fork download
  1. #include <stdio.h>
  2.  
  3. #define SIZE 5
  4. int stack[SIZE];
  5. int sp;
  6.  
  7. void push(int value);
  8. int pop(void);
  9.  
  10. int main(void)
  11. {
  12. sp = 0;
  13. int resp, data;
  14.  
  15. while (1) {
  16. printf("1: push 2: pop 0: end : ");
  17. scanf("%d", &resp);
  18.  
  19. if (!resp) break;
  20.  
  21. switch (resp) {
  22. case 1:
  23. printf("push : ");
  24. scanf("%d", &data);
  25. push(data);
  26. break;
  27. case 2:
  28. pop();
  29. break;
  30. default:
  31. printf("不正な入力です。\n");
  32. break;
  33. }
  34. printf("sp = %d\n", sp);
  35. }
  36.  
  37. printf("\n");
  38. for (int i = 0; i < sp; i++) {
  39. printf("stack[%d] = %d\n", i, stack[i]);
  40. }
  41.  
  42. return 0;
  43. }
  44.  
  45. void push(int value)
  46. {
  47. if (sp >= SIZE) {
  48. printf("スタックが満杯で入りませんでした\n");
  49. } else {
  50. stack[sp++] = value;
  51. }
  52. }
  53.  
  54. int pop(void)
  55. {
  56. if (sp <= 0) {
  57. printf("スタックが空で取り出せませんでした\n");
  58. return 0;
  59. } else {
  60. return stack[--sp];
  61. }
  62. }
  63.  
Success #stdin #stdout 0.01s 5312KB
stdin
1 4
1 2
2
1 3
0
stdout
1: push  2: pop  0: end : push : sp = 1
1: push  2: pop  0: end : push : sp = 2
1: push  2: pop  0: end : sp = 1
1: push  2: pop  0: end : push : sp = 2
1: push  2: pop  0: end : 
stack[0] = 4
stack[1] = 3