前言
作为比较简单的数据结构,使用C++容器库中的栈(std::stack)也相对比较简单。
在头文件中,栈的定义为:
template<
class T,
class Container = std::deque<T>
> class stack;
Stack
常用函数:
- top():访问栈顶
- empty():判断栈空
- size():返回栈中元素数
- push():向栈顶插入元素
- pop():删除栈顶元素
代码
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <stack>
using namespace std;
int main()
{
int n;
while (cin>>n) {
stack<int> s;
string ch;
int val;
while (n--) {
cin>>ch;
if (ch == "PUSH") {
cin>>val;
s.push(val);
} else if (ch == "POP") {
if (!s.empty())
s.pop();
} else if (ch == "TOP") {
if (!s.empty())
cout<<"Top : "<<s.top()<<endl;
else
cout<<"Empty"<<endl;
}
cout<<"Size : "<<s.size()<<endl;
}
cout<<endl;
}
}