题目描述
栈:插入元素和删除元素只能在线性表的一端进行,所以遵循“先进后出 (LIFO) ”原则,其中插入和删除的一端称为栈顶 (top)。我们可以把栈比喻成一个箱子,只能在箱子的开口处放入和取出物体,而且是后放入的物体,会被先取出来。
输入格式
第 1 行一个整数n ,表示有 n 条关于 S的操作,在进行任何操作之前,S 是空的。接来的 N 行,每行 一个关于S的操作,格式和含义如下:
clear:把栈置空。
empty:判断栈是否为空。
push(x):把整数 x 插入栈顶。
pop: 栈顶元素出栈。
top :获取栈顶元素的值。
输出格式
若干行,对应输入中的 top, pop 和 empty 操作:
对于 top 操作,输出一个整数,如果这个操作失败,则输出单词 error。
对于 pop 操作,如果这个操作失败,则输出单词 error。
对于 empty 操作,如果栈是空,则输出 empty,否则输出 not empty。
样例
样例输入
8
push 10
top
push 15
pop
top
clear
pop
empty
样例输出
10
10
error
empty
数据范围与提示
n<20000
x是 int 范围内的整数
#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("A.in", "r", stdin);
freopen("A.out", "w", stdout);
stack<int> a;
long long int n, b;
string x;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
if (x == "clear") {
while (!a.empty()) {
a.pop();
}
}
if (x == "empty") {
if (a.empty()) {
cout << "empty" << endl;
} else {
cout << "not empty" << endl;
}
}
if (x == "pop") {
if (a.empty()) {
cout << "error" << endl;
} else {
a.pop();
}
}
if (x == "top") {
if (a.empty()) {
cout << "error" << endl;
} else {
a.top();
cout << a.top() << endl;
}
}
if (x == "push") {
cin >> b;
a.push(b);
}
}
return 0;
}