原题链接:
大致题意:
后缀序列求值
输入:
23+1+
输出:
6
大致思路:
stack<int> sta;
1.遇到数字则压入栈;
2.遇到运算符每次弹出两个数a, b;进行运算后压入栈;
3.在遍历完表达时候判断栈内是否只有一个元素,有则为最后结果;多于一个元素说明表达式有错误;
代码;
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int ,int> PII;
const int N=1e6+10;
int main()
{
string line;
cin>>line;
stack<int> sta; //栈
for(int i=0;i<line.size();i++)
{
if(line[i]-'0'>=0 && line[i]-'0'<=9)//数字
{
sta.push(line[i]-'0'); //数字入栈
}
else if(line[i]=='+')
{
if(sta.size()>=2)
{
int x=sta.top(); sta.pop();
int y=sta.top(); sta.pop();
sta.push(x+y);
}
}
else
{
if(sta.size()>=2)
{
int x=sta.top(); sta.pop();
int y=sta.top(); sta.pop();
sta.push(x-y);
}
}
}
if(sta.size()==1)
cout<<sta.top()<<endl;
else
cout<<"error";
return 0;
}