stack堆栈容器
头文件:#include<stack>、using namespace std;
先进后出(Last in First out,LIFO)的线性表,插入和删除元素都只能在表的一端进行。插入元素的一端称为栈顶(Stack Top),另一端成为栈底(Stack Bottom)。插入元素叫入栈(Push),元素的删除则称为出栈(Pop)。
堆栈只提供入栈(push())、出栈(pop())、栈顶元素的访问(top())和判断是否为空(empty()),以及返回当前栈堆有几个元素(size())。
【程序】
#include<stack>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int i;
stack<int> s;
for(i=1;i<=4;i++)
s.push(i);
cout<<"栈顶元素:"<<s.top()<<endl;
cout<<"栈堆大小:"<<s.size()<<endl;
cout<<"是否为空:"<<s.empty()<<endl;
while(!s.empty())//while(s.empty()!=true)//while(s.empty()!=1)
{
cout<<s.top()<<" ";
s.pop();//也可以用while和此句来清空栈
}
cout<<endl;
return 0;
}
【运行】
待