stack(栈)
一种先进后出的数据结构
1、头文件
#include<stack>
using namespace std;
2、定义
stack<int>st;
stack<int>st[manx];//st[0]~st[manx-1]中的每一个都是一个容器
stack<stack<int> >st;//>>之间要加空格
//类型名也可以是int、double、char,或者STL标准容器:vector、queue等
3、访问
在STL的stack中只能通过top()来访问栈顶元素
4、常用函数(见表格)
5、示例(见代码)
6、用途:模拟一些递归算法的实现
基本操作 | 复杂度 | |
---|---|---|
push() | push(x)表示将x入栈 | O(1) |
top() | 获得栈顶元素 | O(1) |
pop() | 移除栈顶元素 | O(1) |
empty() | 检测stack是否为空,为true空返回 | O(1) |
size() | 返回stack中元素的个数 | O(1) |
#include<algorithm>
#include<stdio.h>
#include <iostream>
#include<stack>
using namespace std;
stack<int>st;
int main()
{
st.push(12);//加入栈
st.push(1);
st.push(5);
st.push(9);
cout<<st.size()<<endl;
while(!st.empty())//非空
{
printf("%d ",st.top());//栈顶
st.pop();//移出
}
cout<<endl;
}