利用顺序结构实现的一个栈,因栈大小固定,所以内存存在浪费,可利用线性结构实现可变空间 #include using namespace std; int res[100001]; int n; int top = -1; void push(int val) { top++; res[top] = val; } void top1() { if (top == -1) { printf("error\n"); return; } printf("%d\n", res[top]); } void pop() { if (top == -1) { printf("error\n"); return; } printf("%d\n", res[top]); top--; } int main() { scanf("%d\n", &n); for (int i = 0; i < n; i++) { string s; getline(cin, s); int index = s.find(' '); if (index == -1) { if (s == "top") { top1(); }else { pop(); } }else{ string opr = s.substr(0, index); int x = atoi((s.substr(index + 1 , s.size()).c_str())); push(x); } } return 0; }