#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STACK_SIZE 100000 typedef struct stack { int st[MAX_STACK_SIZE]; int index; } stack; stack* push(stack* s, int x) { if (s->index == MAX_STACK_SIZE - 1) { printf("error\n"); exit(1); // 栈满时退出程序 } s->st[++s->index] = x; return s; } void pop(stack* s) { if (s->index == -1) { printf("error\n"); } else { printf("%d\n", s->st[s->index--]); } } void top(stack* s) { if (s->index == -1) { printf("error\n"); } else { printf("%d\n", s->st[s->index]); } } int main() { int n; stack* a = (stack*)malloc(sizeof(stack)); // 动态分配栈内存 a->index = -1; // 初始化index为-1,表示栈为空 while (scanf("%d", &n) != EOF) { for (int i = 0; i < n; i++) { char s[6]; scanf("%s", s); if (strcmp(s,"push") == 0) { int x; scanf("%d", &x); push(a, x); } else if (strcmp(s,"pop") == 0) { pop(a); } else if (strcmp(s,"top") == 0) { top(a); } } } free(a); // 释放栈内存 return 0; }