fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node {
  5. int val;
  6. struct node *next;
  7. } Node;
  8.  
  9. Node *head = NULL;
  10.  
  11. // ノード作成
  12. Node* createN(int x){
  13. Node *newnode;
  14. newnode = (Node *)malloc(sizeof(Node));
  15. newnode->val = x;
  16. newnode->next = NULL;
  17. return newnode;
  18. }
  19.  
  20. // メモリ解放
  21. void freeL(){
  22. Node *p;
  23. while(head != NULL){
  24. p = head->next;
  25. free(head);
  26. head = p;
  27. }
  28. }
  29.  
  30. // リスト出力
  31. void printL(){
  32. Node *p = head;
  33. while(p != NULL){
  34. printf("%d ", p->val);
  35. p = p->next;
  36. }
  37. printf("\n");
  38. }
  39.  
  40. // 先頭に挿入(スタック用)
  41. void insHead(int x){
  42. Node *p = createN(x);
  43. p->next = head;
  44. head = p;
  45. }
  46.  
  47. // 末尾に挿入(キュー用)
  48. void insTail(int x){
  49. Node *p = head;
  50. if(p == NULL){
  51. head = createN(x);
  52. return;
  53. }
  54. while(p->next != NULL){
  55. p = p->next;
  56. }
  57. p->next = createN(x);
  58. }
  59.  
  60. // 先頭を削除
  61. void delHead(){
  62. Node *p = head;
  63. if(head == NULL) return;
  64. head = head->next;
  65. free(p);
  66. }
  67.  
  68. // ---------- スタックの関数 ----------
  69.  
  70. // push:先頭に追加
  71. void push(int x){
  72. insHead(x);
  73. }
  74.  
  75. // pop:先頭を取り出す
  76. int pop(){
  77. if (head == NULL) return -1;
  78. int val = head->val;
  79. delHead();
  80. return val;
  81. }
  82.  
  83. // ---------- キューの関数 ----------
  84.  
  85. // enqueue:末尾に追加
  86. void enqueue(int x){
  87. insTail(x);
  88. }
  89.  
  90. // dequeue:先頭を取り出す
  91. int dequeue(){
  92. if (head == NULL) return -1;
  93. int val = head->val;
  94. delHead();
  95. return val;
  96. }
  97.  
  98. // ---------- メイン関数 ----------
  99. int main(void){
  100. int s1, s2, s3, q1, q2, q3;
  101.  
  102. // スタックテスト
  103. push(1);
  104. push(2);
  105. push(3);
  106. s1 = pop();
  107. s2 = pop();
  108. s3 = pop();
  109. printf("%d %d %d\n", s1, s2, s3); // → 3 2 1
  110.  
  111. // キューテスト
  112. enqueue(1);
  113. enqueue(2);
  114. enqueue(3);
  115. q1 = dequeue();
  116. q2 = dequeue();
  117. q3 = dequeue();
  118. printf("%d %d %d\n", q1, q2, q3); // → 1 2 3
  119.  
  120. freeL(); // メモリ解放
  121. return 0;
  122. }
  123.  
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
3 2 1
1 2 3