#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct stack { int val; struct stack *next; } *Stack, stack; // 头插法入栈 void push(Stack *h, int val) { Stack p = *h; Stack s = (Stack) malloc(sizeof(stack)); s->val = val; s->next = p->next; p->next = s; // printf("%d\n", p->next->val); } // 输出栈顶,栈顶不出栈 void top(Stack h) { if (h->next == NULL) { printf("error\n"); return; } printf("%d\n", h->next->val); } // 输出栈顶,并让栈顶出栈 void pop(Stack *h) { Stack p = *h; if (p->next == NULL) { printf("error\n"); return; } printf("%d\n", p->next->val); p->next = p->next->next; } int main() { // 新建栈头 Stack h, s; h = (Stack) malloc(sizeof(stack)); h->next = NULL; int n; scanf("%d", &n); for (int i = 0; i < n; ++i) { char ope[10]; scanf("%s", ope); if (strcmp(ope, "push") == 0) { int val; scanf("%d", &val); push(&h, val); } else if (strcmp(ope, "pop") == 0) pop(&h); else if (strcmp(ope, "top") == 0) top(h); } return 0; }