您的位置:首页 > 编程语言 > C语言/C++

栈的简单实现——使用C++容器库(STL Stack)

2016-02-06 12:28 316 查看

前言

作为比较简单的数据结构,使用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;
}
}


测试结果



参考资料

http://zh.cppreference.com/w/cpp/container/stack
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 数据结构 C++