这个思路知识点相信大家都可以搜到,我直接放出C++实现的代码,用电栈和队列,为了区别放入队列的是符号还是数字,我们用一个结构体去标识即可
#include<iostream>
#include<map>
#include<stack>
#include<queue>
using namespace std;
//设置优先级
map<char ,int> p;
/*
测试用例:
1 + 2
3
4 + 2 * 5 - 7 / 11
13.36
*/
//初始化
struct node{
double num; //操作数
char op; //操作符
bool flag; //标志:true为操作数,false为操作符
};
//中缀转为后缀并求值 ,没有括号
int main(){
//设置字符优先级
p['+']=p['-'] = 1;
p['*']=p['/'] = 2;
string str;
getline(cin,str);
int len=str.length();
stack<node> s; //符号栈
queue<node> q; //后缀队列
int i=0;
int num=0;
while(i<len){
if(str[i]>='0'&&str[i]<='9'){
while(str[i]>='0'&&str[i]<='9'&&i<len){
num=num*10+str[i]-'0';
i++;
}
node N;
N.num=num;
N.flag=true;
q.push(N);
num=0;
}
else if(str[i]==' '){
i++;
}
else if(str[i]=='+' || str[i]=='-'){
while(!s.empty() && p[s.top().op]>=1 ){
node N=s.top();
s.pop();
q.push(N);
}
node N;
N.op=str[i];
N.flag=false;
s.push(N);
i++;
}
else if(str[i]=='*' || str[i]=='/'){
while(!s.empty() && p[s.top().op]>=2 ){
node N=s.top();
s.pop();
q.push(N);
}
node N;
N.op=str[i];
N.flag=false;
s.push(N);
i++;
}
}
//将栈中剩余的符号出栈
while(!s.empty()){
node N=s.top();
q.push(N);
s.pop();
}
//打印后缀表达式
/*
while(!q.empty()){
node N=q.front();
q.pop();
if(N.flag){
cout<<N.num;
}else{
cout<<N.op;
}
}
cout<<endl;
*/
stack<int> ans;
//进行后缀表达式求值
while(!q.empty()){
node N=q.front();
q.pop();
if(N.flag){
//数字
ans.push(N.num);
}else{
int t2=ans.top();
ans.pop();
int t1=ans.top();
ans.pop();
if(N.op=='+'){
ans.push(t1+t2);
}else if(N.op=='-'){
ans.push(t1-t2);
}else if(N.op=='*'){
ans.push(t1*t2);
}else if(N.op=='/'){
ans.push(t1/t2);
}
}
}
if(!ans.empty())
cout<<ans.top()<<endl;
return 0;
}