fork download
  1. //char型データを格納するためのスタックを構造体として定義し、スタックを実現するための3つの関数を定義せよって問題なんですけど、
  2. //void init(Stack *stack);
  3. //○stackを初期化する
  4. //char push(char c, Stack *stack);
  5. //○stackに c をpushする.返り値はpushが成功したかどうか
  6. //char pop(Stack *stack);
  7. //○stackからデータをpopする.返り値はpopした値.ただし,失敗したときは0を返す。
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11.  
  12. typedef struct TagStackEntry {
  13. char data;
  14. struct TagStackEntry *next;
  15. } StackEntry;
  16.  
  17. typedef struct {
  18. StackEntry *top;
  19. } Stack;
  20.  
  21. void init(Stack *stack)
  22. {
  23. stack->top = NULL;
  24. }
  25.  
  26. char push(char c, Stack *stack)
  27. {
  28. StackEntry *e;
  29. if (c == 0) return 0;
  30. e = malloc(sizeof(StackEntry));
  31. if (e == 0) return '\0';
  32. e->data = c;
  33. e->next = stack->top;
  34. stack->top = e;
  35. return c;
  36. }
  37.  
  38. char pop(Stack *stack)
  39. {
  40. char c;
  41. StackEntry *next;
  42. if (stack->top == NULL)
  43. return 0;
  44. c = stack->top->data;
  45. next = stack->top->next;
  46. free(stack->top);
  47. stack->top = next;
  48. return c;
  49. }
  50.  
  51. int main()
  52. {
  53. // init
  54. Stack stack;
  55. init(&stack);
  56. // push
  57. push('A', &stack);
  58. push('B', &stack);
  59. push('C', &stack);
  60. // pop & show
  61. {
  62. char c;
  63. while ((c = pop(&stack)) != '\0')
  64. printf("%c\n", c);
  65. }
  66. return 0;
  67. }
  68.  
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
C
B
A