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 = malloc(sizeof(StackEntry)); /* このエントリは番兵となる */
  24. stack->top->data = '\0';
  25. stack->top->next = NULL;
  26. }
  27.  
  28. char push(char c, Stack *stack)
  29. {
  30. StackEntry *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 = stack->top->data;
  41. StackEntry *next = stack->top->next;
  42. if (next) {
  43. free(stack->top);
  44. stack->top = next;
  45. }
  46. return c;
  47. }
  48.  
  49. int main()
  50. {
  51. // init
  52. Stack stack;
  53. init(&stack);
  54. // push
  55. push('A', &stack);
  56. push('B', &stack);
  57. push('C', &stack);
  58. // pop & show
  59. {
  60. char c;
  61. while ((c = pop(&stack)) != '\0')
  62. printf("%c\n", c);
  63. }
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
C
B
A