C语言的解法如下:
#include<stdlib.h>
#include<string.h>
#define MAX 100000
typedef struct Stack{
int a[MAX];
int topp;
}*LStack;
void inistack(LStack s){
s->topp=0;
}
void push(LStack s,int x){
s->a[s->topp]=x;
s->topp++;
}
int pop(LStack s){
if(s->topp==0){
return -1;
}
return s->a[--s->topp];
}
int top(LStack s){
if(s->topp==0){
return -1;
}
int num=s->a[--s->topp];
s->topp++;
return num;
}
int main(){
LStack s=(LStack)malloc(sizeof(struct Stack));
inistack(s);
int n=0;
scanf("%d",&n);
while(n--){
char *str=(char*)malloc(6*sizeof(char));
scanf("%s",str);
if(!strcmp(str,"push")){
int num=0;
scanf("%d",&num);
push(s,num);
}
if(!strcmp(str,"pop")){
int num1=pop(s);
if(num1==-1){
printf("error\n");
continue;
}
printf("%d\n",num1);
}
if(!strcmp(str,"top")){
int num2=top(s);
if(num2==-1){
printf("error\n");
continue;
}
printf("%d\n",num2);
}
}
return 0;
}