간단한 스택 구현 문제이다.
아래와 같이 구현해 보았다.
# include <stdio.h>
# include <string.h>
# define MAX_SIZE 10000
typedef int item_t;
typedef struct stack_ {
item_t items[MAX_SIZE];
size_t top;
} stack;
void s_init(stack *s) {
s->top = 0;
}
int is_empty_stack (stack *s) {
if (s->top == 0) return 1;
else return 0;
}
void s_push(stack *s, item_t item) {
s->items[s->top++] = item;
}
int s_pop(stack *s) {
int res;
if (is_empty_stack(s)) res = -1;
else {
res = s->items[s->top - 1];
s->top--;
}
return res;
}
int main(void) {
int N;
scanf("%d", &N);
stack s;
s_init(&s);
for (int i = 0;i < N;i++) {
char str[6];
scanf(" %s", str);
if (!strcmp("push", str)) {
int item;
scanf("%d", &item);
s_push(&s, item);
}
else if (!strcmp("pop", str)) {
printf("%d\n", s_pop(&s));
}
else if (!strcmp("size", str)) {
printf("%d\n", s.top);
}
else if (!strcmp("empty", str)) {
printf("%d\n", is_empty_stack(&s));
}
else if (!strcmp("top", str)){
if (is_empty_stack(&s)) printf("-1\n");
else {
printf("%d\n", s.items[s.top - 1]);
}
}
}
return 0;
}