package datastructure;
public class Postfix {
/**
* 转为后缀表达式:
* 1、如果是"("直接压入栈。
* 2、如果是")",依次从栈弹出运算符加到postfix的末尾,直到遇到"(";
* 3、如果是运算符,比较扫描到的运算符,和栈顶的运算符。如果扫描到的运算符优先级
* 高于栈顶运算符则,把运算符压入栈。否则的话,就依次把栈中运算符弹出加到postfix的末尾,
* 直到遇到优先级低于扫描到的运算符或栈空,并且把扫描到的运算符压入栈中。就这样依次扫描,知道结束为止。
* 如果是操作数,直接加到postfix末尾
* 如果扫描结束,栈中还有元素,则依次弹出加到postfix的末尾。
*/
public static void main(String[] args) throws Exception {
String str="a+(b-c/d)*e";//输出abcd/-e*+则正确
System.out.println(convertToPostfix(str));
}
public static String convertToPostfix(String str) {
LinkStack ls= new LinkStack();
String postfix=new String();
for(int i=0;i<str.length()&&str!=null;i++){
char c=str.charAt(i);
if(c=='(') //为开括号
ls.push(c);
else if(c==')') //为闭括号
{
char tmp=(Character) ls.pop();
while(tmp!='(')
{
postfix=postfix.concat(String.valueOf(tmp));
tmp=(Character) ls.pop();
}
}
else if(isOperator(c)) //为运算符
{
if(!ls.isEmpty()) //判断栈中存不存在元素
{
char tmp =(Character) ls.pop();
while(priority(tmp)>=priority(c)){
postfix=postfix.concat(String.valueOf(tmp));
tmp=(Character) ls.pop();
}
if(priority(tmp)<priority(c))
{
ls.push(tmp);
ls.push(c);
}
}
else //空栈直接push
ls.push(c);
}
else{ //操作数直接输出到字符串后
postfix=postfix.concat(String.valueOf(c));
}
}
while(!ls.isEmpty())
postfix=postfix.concat(String.valueOf(ls.pop()));
return postfix;
}
public static int priority(char c) {
if(c=='^')
return 3;
if(c=='*'||c=='/'||c=='%')
return 2;
if(c=='+'||c=='-')
return 1;
else
return 0;
}
public static boolean isOperator(char c) {
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='%'||c=='^')
return true;
else
return false;
}
}
转载自:https://www.cnblogs.com/xurui1995/p/5183182.html
算术表达式转成后缀表达式
最新推荐文章于 2021-08-16 18:01:53 发布