Cmain.c · 93 行#include <stdio.h>#include <string.h> typedef struct Node { int val; struct Node *next;} Node; typedef struct { Node *head; /* 첫 칸(비었으면 NULL) */ Node **tailp; /* 마지막 칸의 next 자리(비었으면 &head): 여기에 붙이면 맨 뒤 */} Train; static Node pool[10000]; /* 명령마다 칸은 많아야 하나 생긴다 */static int used = 0; Node *new_node(int val) { Node *nd = &pool[used++]; nd->val = val; nd->next = NULL; return nd;} /* 기차를 바꾸는 함수는 모두 Train의 주소를 받는다 */void push_front(Train *t, Node *nd) { nd->next = t->head; if (t->head == NULL) t->tailp = &nd->next; t->head = nd;} void push_back(Train *t, Node *nd) { *t->tailp = nd; t->tailp = &nd->next;} /* pp는 "지금 칸을 가리키는 포인터"의 주소: 첫 칸이든 가운데 칸이든 똑같이 *pp만 바꾸면 떼어진다 */void cut(Train *t, int x) { for (Node **pp = &t->head; *pp != NULL; pp = &(*pp)->next) { if ((*pp)->val == x) { Node *gone = *pp; *pp = gone->next; if (gone->next == NULL) t->tailp = pp; /* 마지막 칸을 뗐으면 붙일 자리가 앞으로 온다 */ return; } }} void reverse(Train *t) { Node *prev = NULL, *cur = t->head; t->tailp = cur ? &cur->next : &t->head; /* 지금 첫 칸이 뒤집은 뒤 마지막 칸 */ while (cur != NULL) { Node *next = cur->next; cur->next = prev; prev = cur; cur = next; } t->head = prev;} void show(const Train *t) { int k = 0; for (const Node *p = t->head; p != NULL; p = p->next) k++; printf("%d", k); for (const Node *p = t->head; p != NULL; p = p->next) printf(" %d", p->val); printf("\n");} int main(void) { int q, x; char cmd[8]; Train t; t.head = NULL; t.tailp = &t.head; scanf("%d", &q); for (int i = 0; i < q; i++) { scanf("%7s", cmd); if (strcmp(cmd, "front") == 0) { scanf("%d", &x); push_front(&t, new_node(x)); } else if (strcmp(cmd, "back") == 0) { scanf("%d", &x); push_back(&t, new_node(x)); } else if (strcmp(cmd, "cut") == 0) { scanf("%d", &x); cut(&t, x); } else if (strcmp(cmd, "rev") == 0) { reverse(&t); } else { show(&t); } } return 0;}