C++ STL stack(栈)

#include <stack> //STL -- stack 头文件
stack <int> s; //定义栈
s.pop(); //从栈顶删除元素;
s.push(); //从栈顶入栈
s.top(); //取栈顶元素,但不删除

例:逆波兰式

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
//#define ISA_XR
using namespace std;
stack <int> s;
int main()
{
#ifdef ISA_XR
freopen("Reverse_Polish_notation.in","r",stdin);
freopen("Reverse_Polish_notation.out","w",stdout);
#endif
string in;
while( cin>>in ) //读入。。。
{
//读入为符号 则取栈顶两元素进行相应运算
if(in[0] == '+')
{
int a = s.top();s.pop();
int b = s.top();s.pop(); //取栈顶2各元素,赋给a,b,删除两元素
s.push(a + b); //运算。。
}
else if(in[0] == '-')
{
int a = s.top();s.pop();
int b = s.top();s.pop();
s.push(b - a);
}
else if(in[0] == '*')
{
int a = s.top();s.pop();
int b = s.top();s.pop();
s.push(a * b);
}
else s.push(atoi(in.c_str())); //如果读入为数 则入栈
}
cout<<s.top(); //输出栈顶元素---最终运算结果;

#ifdef ISA_XR
fclose(stdin);
fclose(stdout);
#endif
return 0;
}

猜你喜欢

转载自www.cnblogs.com/xrisa/p/11185494.html