栈c++代码实现
//實在不想寫數組法了,寫個常用的STL的吧
#include?"iostream"
#include?"algorithm"
#include?"stack"
using?namespace?std;
?
void?Init(stack?<int>?s)
{
while(!s.empty())
{
s.pop();
}
}
?
int?main()
{
stack?<int>?s;
int?n,q;
while(cin>>n>>q)
{
Init(s);//初始化
for(int?i=0;i<n;i++)
{
int?key;
cin>>key;
s.push(key);
}
while(q--)
{
int?x;
cin>>x;
if(x==1)//出棧
{
if(!s.empty())
s.pop();
}
else?if(x==2)//顯示棧頂
{
if(!s.empty())
cout<<s.top()<<endl;
}
if(x==3) //進棧
{
int?key;
cin>>key;
s.push(key);
}
}
}
}
總結
- 上一篇: c++堆栈中 top() pop()的具
- 下一篇: C++:构造函数和析构函数能否为虚函数