import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
/**
* 输入 a/(b-c)+d*e
* 输出 abc-/de*+
*/
public class Houzhui {
public static void main(String[] args)
{
Map<Character,Integer> mapInside = new HashMap<>();
mapInside.put('(',1);
mapInside.put(')',9);
mapInside.put('+',2);
mapInside.put('-',2);
mapInside.put('*',3);
mapInside.put('/',3);
Map<Character,Integer> mapOutside = new HashMap<>();
mapOutside.put('(',9);
mapOutside.put(')',1);
mapOutside.put('+',2);
mapOutside.put('-',2);
mapOutside.put('*',3);
mapOutside.put('/',3);
Scanner in = new Scanner(System.in);
String str = in.next();
Stack<Character> stack = new Stack<Character>();
for(int i = 0;i<str.length();i++)
{
char singleCharstr = str.charAt(i);
if(zimu(singleCharstr))
{
print(singleCharstr);
}else
{
if (stack.isEmpty()) {
stack.push(singleCharstr);
} else {
while (!stack.isEmpty()) {
Character character = stack.pop();
if (mapOutside.get(singleCharstr) > mapInside.get(character)) {
stack.push(character);
stack.push(singleCharstr);
break;
} else {
print(character);
}
}
}
}
}
while(!stack.isEmpty()) {
Character character = stack.pop();
print(character);
}
}
private static boolean zimu(char s)
{
if(Integer.valueOf(s) >= Integer.valueOf('a') && Integer.valueOf(s) <= Integer.valueOf('z'))
{
return true;
}
return false;
}
private static void print(char s)
{
if(Integer.valueOf(s) == Integer.valueOf('(') || Integer.valueOf(s) == Integer.valueOf(')'))
{
return;
}
System.out.print(s);
}
}
中缀表达式转化为后缀表达式(java实现)
最新推荐文章于 2022-08-25 13:10:53 发布