#include<stdio.h> #include<string.h> #define Max_Size 100000 #define true 1 #define false 0 typedef int _bool; typedef struct{ int data[Max_Size]; int top; }Struct; void Init_Struct(Struct *S);//初始化栈 _bool push(Struct* S,int e);//将e入栈 _bool pop(Struct* S);//栈顶出栈 void top(Struct* S);//读栈顶元素 int main(void){ Struct S; Init_Struct(&S);//初始化栈S int n = 0;//存储题目输入的n,代表操作次数 scanf("%d",&n); char str[5];//存储输入的操作名 int x = 0;//存储入栈时将入栈的元素 while(n > 0){ scanf("%s",str); if(strcmp(str,"push") == 0){ scanf("%d",&x); push(&S,x); } else if(strcmp(str,"pop") == 0){ if(pop(&S) == false){ printf("error\n"); } } else if(strcmp(str,"top") == 0){ top(&S); } n--; for(int i = 0; i < 4;i++){ str[i] = ' '; }//将数组初始化不然影响下次输入后的比较 } return 0; } void Init_Struct(Struct *S){ S->top = -1; } _bool push(Struct* S,int e){ if(S->top == Max_Size - 1){ return false;//栈已满 } S->top = S->top + 1; S->data[S->top] = e; return true; } _bool pop(Struct* S){ if(S->top == -1){ return false;//栈为空 } printf("%d\n",S->data[S->top]); S->top = S->top - 1; return true; } void top(Struct* S){ if(S->top == -1){ //栈为空 printf("error\n"); return ; } printf("%d\n",(S->data[S->top])); }