#include<iostream>
#include<stack>
using namespace std;
//栈外优先级
int getBeforeIn(char op){
switch(op){
case '+':
case '-':
return 2;
case '*':
case '/':
case '%':
return 4;
case '(':
return 8;
case ')':
return 1;
case '#':
return 0;
default:
return -1;
}
}
//栈内的优先级
int getAfterIn(char op){
switch(op){
case '+':
case '-':
return 3;
case '*':
case '/':
case '%':
return 5;
case '(':
return 1;
case ')':
return 8;
case '#':
return 0;
}
}
int main(){
stack<char> s;
s.push('#');
char ch;
while(cin>>ch){
//判断如果是操作数就直接输出
if(getBeforeIn(ch)==-1){
cout<<ch;
}
//判断如果是操作符右括号“)”
else if(getBeforeIn(ch)==1){
while(getAfterIn(s.top())>1){
cout<<s.top();
s.pop();
}
s.pop();
}
//判断如果是栈外操作符优先级大于栈内操作符优先级
else if(getBeforeIn(ch)>=0&&getBeforeIn(ch)>getAfterIn(s.top())){
s.push(ch);
}
//判断如果是栈外操作符优先级小于栈内操作符优先级
else if(getBeforeIn(ch)>=0&&getBeforeIn(ch)<getAfterIn(s.top()))
{
while(getBeforeIn(ch)<getAfterIn(s.top())){
cout<<s.top();
s.pop();
}
s.push(ch);
}
//判断如果是操作符#
else if(getBeforeIn(ch)==0&&getAfterIn(s.top())==0){
return 0;
}
}
return 0;
}
c++通过栈将中缀表达式转成后缀表达式
最新推荐文章于 2020-10-27 16:47:09 发布