java中缀转后缀表达式
主要记录学习
1.规则
a.如果是数直接输出
b.如果不是数
b1.符号为“(”直接插入到符号栈中
b2.符号为“)”,在遇到“(”之前一直出栈并输出;符号"("不输出
if (e.equals(")")) {
while (true) {
if (stack.peek().equals("("))
{stack.pop();
break;}
res = res + stack.pop();
}
continue;
}
b3.如果符号是"±*/"则看他们的优先级
比较当前字符和栈顶字符
如果当前字符的优先级大于栈顶直接入栈
如果当前字符的优先级小于或者等于栈顶字符则在栈空或者当前字符的优先级大于栈顶字符前一直出栈并输出,最后当前字符入栈
if (comparePriority(e,stack.peek())){
stack.push(e);
}else{
while(true){
if(stack.isEmpty()){
stack.push(e);
break;
}else{
if(comparePriority(e, stack.peek())){
stack.push(e);
break;
}
}
res = res + stack.pop();
}
}
demo
public class qianzhui2houzhui {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
String expression = "1 + 2 * 3 + ( 4 * 5 + 6 ) * 7";
String[] temp_arr = expression.split(" ");
List<String> elist = new ArrayList<String>(Arrays.asList(temp_arr));
String res = "";
for (String e : elist) {
if (e.matches("\\d+")) {
res = res + e;
} else {
if (stack.isEmpty())
stack.push(e);
else {
if (e.equals(")")) {
while (true) {
if (stack.peek().equals("("))
{stack.pop();
break;}
res = res + stack.pop();
}
continue;
}
if (e.equals("(")) {
stack.push("(");
continue;
}
if (comparePriority(e,stack.peek())){
stack.push(e);
}else{
while(true){
if(stack.isEmpty()){
stack.push(e);
break;
}else{
if(comparePriority(e, stack.peek())){
stack.push(e);
break;
}
}
res = res + stack.pop();
}
}
}
}
}
for(String e:stack){
res = res+e;
}
System.out.println(res);
}
static int isPriority(String str){
if(str.equals("*")||str.equals("/")) return 1;
if(str.equals("+")||str.equals("-")) return 0;
return -1;
}
//比较优先级
static boolean comparePriority(String e1,String e2){
return isPriority(e1)>isPriority(e2);
}
}