后缀表达式
中缀表达式转后缀表达式
后缀表达式: 所有的符号都是在要计算的数字后面,并且没有括号。
规则:
从左到右遍历中缀表达式每个数字和符号,若是数字就输出,若是符号,则判断其与栈顶符号的优先级,是右括号或优先级不高于栈顶符号(乘除优先加减),则栈顶元素依次出栈并输出,并将当前符号进栈。
判断优先级
int prio(char op){
int priority;
if(op=='*'||op=='/') priority=2;
if(op=='+'||op=='-') priority=1;
//左括号低
if(op=='(') priority=0;
return priority;
}
bool Trans(string &str,string &str1){
stack<char> s;
for(int i=0;i<str.size();i++){
//如果是数字直接输出
if(str[i]>='0'&&str[i]<='9'){
str1+=str[i];
}else{
//使不同的数字隔开
str1+=" ";
//栈空则直接入栈
if(s.empty()) s.push(str[i]);
else if(str[i]=='(') s.push('(');
else if(str[i]==')'){
while(s.top()!='('){
str1+=s.top();
s.pop();
}
//弹出左括号
s.pop();
}else{
while(prio(str[i])<=prio(s.top())){
str1+=s.top();
s.pop();
if(s.empty()) break;
}
s.push(str[i]);
}
}
}
while(!s.empty()){
str1+=s.top();
s.pop();
}
return true;
}
调整后缀表达式
void deletespace(string &str){
int i=0;
while(i<str.size()){
//如果数字后面有两个空格删去一个空格
if(i<str.size()-1&&str[i]==str[i+1]&&str[i]==' '){
str.erase(i,1);
//如果符号后面有一个空格删去
}else if(i<str.size()-1&&(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')&&str[i+1]==' '){
str.erase(i+1,1);
//符号前面是数字,插入一个空格
}else if(str[i-1]>='0'&&str[i-1]<='9'&&(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')){
// cout<<"插入成功";
str.insert(i,1,' ');
}
i++;
}
}
后缀表达式的计算
**规则:**从左到右遍历表达式的每一个数字和符号,遇到数字就进栈,遇到是符号,就将处于栈顶的两个数字出栈,进行运算,将结果进栈,一直到最终获得结果
字符串要经过deletespace()函数处理
void calculate(string str){
stack<double> s;
double x=0.0,x1,x2;
for(int i=0;i<str.size();i++){
switch(str[i]){
case '+':x1=s.top();s.pop();x2=s.top();s.pop();s.push(x1+x2);break;
case '-':x1=s.top();s.pop();x2=s.top();s.pop();s.push(x2-x1);break;
case '*':x1=s.top();s.pop();x2=s.top();s.pop();s.push(x1*x2);break;
case '/':x1=s.top();s.pop();x2=s.top();s.pop();s.push(x2/x1);break;
case ' ':s.push(x);x=0.0;break;
default:x=x*10+str[i]-'0';break;
}
}
cout<<s.top()<<endl;
}