回答編集履歴

2

追記

2021/05/22 07:57

投稿

episteme
episteme

スコア16614

test CHANGED
@@ -171,3 +171,185 @@
171
171
  }
172
172
 
173
173
  ```
174
+
175
+
176
+
177
+ [おまけ] 僕ならこう書く
178
+
179
+ ```C
180
+
181
+ #include<stdio.h>
182
+
183
+ #include<stdlib.h>
184
+
185
+ #include<string.h>
186
+
187
+
188
+
189
+ struct cell {
190
+
191
+ char c;
192
+
193
+ struct cell* next;
194
+
195
+ };
196
+
197
+
198
+
199
+ typedef struct stack_t {
200
+
201
+ struct cell* head;
202
+
203
+ } stack;
204
+
205
+
206
+
207
+ void initialize(stack* stk) {
208
+
209
+ stk->head = NULL;
210
+
211
+ }
212
+
213
+
214
+
215
+ //スタックの内容を表示する
216
+
217
+ void print_stack(const stack* stk) {
218
+
219
+ struct cell* p = stk->head;
220
+
221
+ while (p != NULL) {
222
+
223
+ printf(" -> %c", p->c);
224
+
225
+ p = p->next;
226
+
227
+ }
228
+
229
+ printf("\n");
230
+
231
+ }
232
+
233
+
234
+
235
+ //pushする
236
+
237
+ void push(stack* stk, char s) {
238
+
239
+ struct cell* p = (struct cell*)malloc(sizeof(struct cell));
240
+
241
+ p->c = s;
242
+
243
+ p->next = stk->head;
244
+
245
+ stk->head = p;
246
+
247
+ }
248
+
249
+
250
+
251
+ //popする(空のときは'\0'を返す)
252
+
253
+ char pop(stack* stk) {
254
+
255
+ char c = '\0';
256
+
257
+ if ( stk->head != NULL) {
258
+
259
+ struct cell* tmp = stk->head->next;
260
+
261
+ c = stk->head->c;
262
+
263
+ free(stk->head);
264
+
265
+ stk->head = tmp;
266
+
267
+ }
268
+
269
+ return c;
270
+
271
+ }
272
+
273
+
274
+
275
+ // スタックを空にする
276
+
277
+ void clear(stack* stk) {
278
+
279
+ struct cell* p = stk->head;
280
+
281
+ while (p != NULL) {
282
+
283
+ struct cell* q = p->next;
284
+
285
+ free(p);
286
+
287
+ p = q;
288
+
289
+ }
290
+
291
+ stk->head = NULL;
292
+
293
+ }
294
+
295
+
296
+
297
+ int main(void) {
298
+
299
+ stack stk;
300
+
301
+ initialize(&stk);
302
+
303
+ char line[64];
304
+
305
+ do {
306
+
307
+ printf("pushする文字かpop/endを入力して下さい --> ");
308
+
309
+ scanf("%s", line);
310
+
311
+ if (strcmp(line, "end") == 0) {
312
+
313
+ } else if (strcmp(line, "pop") == 0) {
314
+
315
+ char c = pop(&stk);
316
+
317
+ print_stack(&stk);
318
+
319
+ if ( c != '\0' ) {
320
+
321
+ printf("popされた文字は %c です\n", c);
322
+
323
+ } else {
324
+
325
+ printf("スタックは空です\n");
326
+
327
+ }
328
+
329
+ } else if (strlen(line) != 1) {
330
+
331
+ printf("不正な入力です\n");
332
+
333
+ break;
334
+
335
+ } else {
336
+
337
+ push(&stk, line[0]);
338
+
339
+ print_stack(&stk);
340
+
341
+ }
342
+
343
+ } while (strcmp(line, "end") != 0);
344
+
345
+ clear(&stk);
346
+
347
+ printf("スタックを空にしました\n");
348
+
349
+ printf("プログラムを終了します\n");
350
+
351
+ return 0;
352
+
353
+ }
354
+
355
+ ```

1

微修正

2021/05/22 07:57

投稿

episteme
episteme

スコア16614

test CHANGED
@@ -144,7 +144,7 @@
144
144
 
145
145
  if ( c != '\0' ) {
146
146
 
147
- printf("popされた文字は %c です\n", pop());
147
+ printf("popされた文字は %c です\n", c);
148
148
 
149
149
  }
150
150