回答編集履歴
2
追記
answer
CHANGED
@@ -84,4 +84,95 @@
|
|
84
84
|
} while (strcmp(line, "end") != 0);
|
85
85
|
return 0;
|
86
86
|
}
|
87
|
+
```
|
88
|
+
|
89
|
+
[おまけ] 僕ならこう書く
|
90
|
+
```C
|
91
|
+
#include<stdio.h>
|
92
|
+
#include<stdlib.h>
|
93
|
+
#include<string.h>
|
94
|
+
|
95
|
+
struct cell {
|
96
|
+
char c;
|
97
|
+
struct cell* next;
|
98
|
+
};
|
99
|
+
|
100
|
+
typedef struct stack_t {
|
101
|
+
struct cell* head;
|
102
|
+
} stack;
|
103
|
+
|
104
|
+
void initialize(stack* stk) {
|
105
|
+
stk->head = NULL;
|
106
|
+
}
|
107
|
+
|
108
|
+
//スタックの内容を表示する
|
109
|
+
void print_stack(const stack* stk) {
|
110
|
+
struct cell* p = stk->head;
|
111
|
+
while (p != NULL) {
|
112
|
+
printf(" -> %c", p->c);
|
113
|
+
p = p->next;
|
114
|
+
}
|
115
|
+
printf("\n");
|
116
|
+
}
|
117
|
+
|
118
|
+
//pushする
|
119
|
+
void push(stack* stk, char s) {
|
120
|
+
struct cell* p = (struct cell*)malloc(sizeof(struct cell));
|
121
|
+
p->c = s;
|
122
|
+
p->next = stk->head;
|
123
|
+
stk->head = p;
|
124
|
+
}
|
125
|
+
|
126
|
+
//popする(空のときは'\0'を返す)
|
127
|
+
char pop(stack* stk) {
|
128
|
+
char c = '\0';
|
129
|
+
if ( stk->head != NULL) {
|
130
|
+
struct cell* tmp = stk->head->next;
|
131
|
+
c = stk->head->c;
|
132
|
+
free(stk->head);
|
133
|
+
stk->head = tmp;
|
134
|
+
}
|
135
|
+
return c;
|
136
|
+
}
|
137
|
+
|
138
|
+
// スタックを空にする
|
139
|
+
void clear(stack* stk) {
|
140
|
+
struct cell* p = stk->head;
|
141
|
+
while (p != NULL) {
|
142
|
+
struct cell* q = p->next;
|
143
|
+
free(p);
|
144
|
+
p = q;
|
145
|
+
}
|
146
|
+
stk->head = NULL;
|
147
|
+
}
|
148
|
+
|
149
|
+
int main(void) {
|
150
|
+
stack stk;
|
151
|
+
initialize(&stk);
|
152
|
+
char line[64];
|
153
|
+
do {
|
154
|
+
printf("pushする文字かpop/endを入力して下さい --> ");
|
155
|
+
scanf("%s", line);
|
156
|
+
if (strcmp(line, "end") == 0) {
|
157
|
+
} else if (strcmp(line, "pop") == 0) {
|
158
|
+
char c = pop(&stk);
|
159
|
+
print_stack(&stk);
|
160
|
+
if ( c != '\0' ) {
|
161
|
+
printf("popされた文字は %c です\n", c);
|
162
|
+
} else {
|
163
|
+
printf("スタックは空です\n");
|
164
|
+
}
|
165
|
+
} else if (strlen(line) != 1) {
|
166
|
+
printf("不正な入力です\n");
|
167
|
+
break;
|
168
|
+
} else {
|
169
|
+
push(&stk, line[0]);
|
170
|
+
print_stack(&stk);
|
171
|
+
}
|
172
|
+
} while (strcmp(line, "end") != 0);
|
173
|
+
clear(&stk);
|
174
|
+
printf("スタックを空にしました\n");
|
175
|
+
printf("プログラムを終了します\n");
|
176
|
+
return 0;
|
177
|
+
}
|
87
178
|
```
|
1
微修正
answer
CHANGED
@@ -71,7 +71,7 @@
|
|
71
71
|
} else if (strcmp(line, "pop") == 0) {
|
72
72
|
char c = pop();
|
73
73
|
if ( c != '\0' ) {
|
74
|
-
printf("popされた文字は %c です\n",
|
74
|
+
printf("popされた文字は %c です\n", c);
|
75
75
|
}
|
76
76
|
} else if (strlen(line) != 1) {
|
77
77
|
printf("不正な入力です\n");
|