题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 1000000 typedef struct Test{ int slen; int* base,*top; }test; void init(test* t) { t->slen=MAX; t->base=malloc(sizeof(int)*MAX); t->top=t->base; } void push(test* t, int n) { if(t->top - t->base == t->slen) return; *(t->top) = n; t->top++; } int pop(test* t) { if(t->base == t->top) return 0; t->top--; int ret = *(t->top); return ret; } int top(test* t) { if(t->base == t->top) return 0; return *(t->top-1); } int main() { int n; scanf("%d", &n); test sta; init(&sta); for(int i=0; i<n; i++) { char s[10] = {0}; int t; scanf("%s %d", s, &t); if(strcmp("push", s) == 0) { push(&sta, t); } else if(strcmp("pop", s) == 0) { int ret = pop(&sta); if(ret) printf("%d\n", ret); else printf("error\n"); } else { int ret = top(&sta); if(ret) printf("%d\n", ret); else printf("error\n"); } } free(sta.base); return 0; }