STL中需要用到stack库实现对栈的支持。
栈的构造,一般只用来构造空栈。
#include<stack>
stack<int> s;
入栈与出栈:
s.push(2);
cout<<s.top()<<endl;
s.push(3);
cout<<s.top()<<endl;
cout<<"size = "<<s.size()<<endl;
s.pop();
cout<<s.top()<<endl;
cout<<"size = "<<s.size()<<endl;
输出:
2
3
size = 2
2
size = 1
top是有返回值的,返回栈顶元素。pop没有返回值。
例子说明,进制转化:
int itob(int decimal) //itob需要了解一下 经常用到
{
stack<int> s;
int res = 0;
while(decimal!=0){
s.push(decimal%2);
decimal/=2;
}
while(!s.empty())
{
res=res*10+s.top();
s.pop();
}
return res;
}
十进制转为二进制。主要就是逆序相乘的过程,当然用数组逆序实现也可。