题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <iostream> #include<cstdio> #include<cstdlib> #include<cstring> #define maxsize 100000 using namespace std; typedef struct stack { int* top; int* base; }stack; void initstack(stack &S) { S.base=new int[maxsize]; S.top=S.base; } void pushstack(stack &S,int e) { *S.top=e; S.top++; } void popstack(stack &S) { if(S.top==S.base) printf("error\n"); else { S.top--; printf("%d\n",*S.top); } } void topstack(stack &S) { if(S.top==S.base) printf("error\n"); else { printf("%d\n",*(S.top-1)); } } int main() { void initstack(stack &S); void pushstack(stack &S,int e); void popstack(stack &S); void topstack(stack &S); int a,b,i; stack s; initstack(s); char p[maxsize]; scanf("%d",&a); for(i=1;i<=a;i++) { scanf("%s",p); if(strcmp(p,"push")==0) { scanf("%d",&b); pushstack(s,b); } if(strcmp(p,"pop")==0) popstack(s); if(strcmp(p,"top")==0) topstack(s); } return 0; }