Easy - STL-stack
给定一个初始为空的栈,执行下面几种操作n次:
1 x :表示在栈顶添加数字x x(1 ≤ x ≤ 100)。
2 :输出栈顶的数字。
3 :删除栈顶的数字(保证此时栈不为空)。
4 :输出栈中含有的数字个数。
Input
第一行,一个整数n(1 ≤ n ≤ 20),表示操作的次数。
第2到n+1行,表示每一种操作。
Output
每次操作如果需要输出则输出一行数字。
Sample 1
Inputcopy | Outputcopy |
---|---|
7 1 7 2 1 6 2 3 4 2 |
7 6 1 7 |
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int n;
cin >> n;
stack<int> s;
for (int i = 0; i < n; i++)
{
int step;
cin >> step;
if (step == 1)
{
int x;
cin >> x;
s.push(x);
}
else if (step == 2)
{
if (!s.empty())
{
cout << s.top() << endl;
}
}
else if (step == 3)
{
if (!s.empty())
{
s.pop();
}
}
else if (step == 4)
{
cout << s.size() << endl;
}
}
}