实现一个栈,栈初始为空,支持四种操作:
-
push x
– 向栈顶插入一个数 x;
-
pop
– 从栈顶弹出一个数;
-
empty
– 判断栈是否为空;
-
query
– 查询栈顶元素。
/*
用数组模拟栈
栈:先进后出
*/
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
// tt:栈顶下标
int stk[N], tt;
// 初始化
void init()
{
tt = 0;
}
// 插入一个数x
void push(int x)
{
stk[++tt] = x;
}
// 从栈顶弹出一个数
void pop()
{
tt --;
}
// 判断栈是否为空
bool IsEmpty()
{
// tt = 0 为空
if(tt) return false;
return true;
}
// 查询栈顶元素
void query(int &k)
{
k = stk[tt];
}
int main()
{
init();
int m;
cin >> m;
while(m--)
{
string op;
int x, k;
cin >> op;
if(op == "push")
{
cin >> x;
push(x);
}
else if(op == "pop")
{
if(! IsEmpty()) pop();
}
else if(op == "empty")
{
if(IsEmpty()) cout << "YES" << endl;
else cout << "NO" << endl;
}
else if(op == "query")
{
if(! IsEmpty())
{
query(k);
cout << k << endl;
}
}
}
return 0;
}