题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h> #define max 100000 typedef struct yuntian { int a[max]; int pop; }* yuntian; void init(yuntian s) { s->pop = 0; } void push(yuntian s, int i) { s->a[++s->pop] = i; } int pop(yuntian s) { if (s->pop == 0) return 0; return s->a[s->pop--]; } int top(yuntian s) { if (s->pop == 0) return 0; return s -> a[s -> pop]; } int main() { int a, b; int r; char c[100]; yuntian s = (yuntian)malloc(sizeof(struct yuntian)); init(s); scanf("%d", &a); while (a--) { scanf("%s", c); if (strcmp(c, "push") == 0) { scanf("%d", &b); push(s, b); } else if (strcmp(c, "pop") == 0) { r = pop(s); if (r) { printf("%d\n", r); } else printf("error\n"); } else if (strcmp(c, "top") == 0) { r = top(s); if (r) { printf("%d\n", r); } else printf("error\n"); } } return 0; }