stack
是 C++ 标准模板库(STL)中的容器适配器,用于实现后进先出(LIFO)的栈数据结构。栈中的元素按照后进先出的顺序进行排列,最后插入的元素最先被删除。
特点:
-
后进先出(LIFO):栈中的元素按照后进先出的顺序进行排列,最后插入的元素最先被删除。
-
只能在一端操作:只能在栈的一端(称为栈顶)添加或删除元素,即不能在栈的中间位置插入或删除元素。
-
动态操作:可以动态地向栈中添加元素,并且可以删除栈中的元素,栈会自动调整元素的位置。
- stack的定义
stack<typename> name;
- stack容器内元素的访问
由于栈本身就是一种先进先出的数据结构,在STL中只能通过top()来访问栈顶元素。
示例:
#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
int main()
{
for(int i=0;i<5;i++){
s.push(i+1); //将i+1压入栈
}
cout<<s.top();
return 0;
}
输出结果:
5
- stack常用函数
(1)push()
push(x)将x入栈,时间复杂度为O(1)。
(2)top()
top()获得栈顶元素,时间复杂度为O(1)。
(3)pop()
pop()可以弹出栈顶元素,时间复杂度为O(1)。
示例:
#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
int main()
{
for(int i=0;i<5;i++){
s.push(i+1); //将i+1压入栈
}
for(int i=0;i<2;i++){
s.pop(); //连续两次将栈顶元素出栈(5,4)
}
cout<<s.top();
return 0;
}
输出结果:
3
(4)empty()
empty()可以检测stack内是否为空,返回true为空,返回false为非空,时间复杂度为O(1)。
示例:
#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
int main()
{
if(s.empty()==true){ //栈开始为空
cout<<"empty"<<endl;
}
else{
cout<<"not empty"<<endl;
}
s.push(1); //入栈1后,栈非空
if(s.empty()==true){
cout<<"empty"<<endl;
}
else{
cout<<"not empty"<<endl;
}
return 0;
}
输出结果:
empty
not empty
(5)size()
size()返回stack内元素的个数,时间复杂度为O(1)。
示例:
#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
int main()
{
for(int i=0;i<5;i++){
s.push(i+1); //将i+1入栈
}
cout<<s.size();
return 0;
}
输出结果:
5