中缀表达式:就是我们经常使用的算式,例如 1+(2-3)*4+10/5
后缀表达式:后缀表达式也叫逆波兰表达式,其求值过程可以用到栈来辅助存储,因为机器不识别中缀表达式,我们常常要转换成前缀或者后缀进行计算。
实现过程:通过栈
首先 将 1 进行记录,利用StringBuffer的append()追加 postifx=1
遇到 + 进行压栈 postifx=1
遇到 ( 压栈 postifx=1
2 进行追加 postifx=1 2
- 压栈 postifx=1 2
-3 追加 postifx=1 2 3
遇到 ) 时,将()之间的进行出栈 postifx=1 2 3 -
* 进行压栈 postifx=1 2 3 -
4 追加 postifx=1 2 3 - 4
+ 进行出栈 * + postifx=1 2 3 - 4 * +
10 追加 postifx=1 2 3 - 4 * + 10
/ 压栈 postifx=1 2 3 - 4 * + 10
5 追加 postifx=1 2 3 - 4 * + 10 5
判断为空 全部出栈 postifx=1 2 3 - 4 * + 10 5/ +
总结:出栈时当优先级低的进入栈时,将符号优先级高的进行压栈,如果遇到右括号,输出左右括号之间的,如果字符最后为空进行全部压栈
import java.util.Stack;
public class toPostfix {
public static StringBuffer toPostfix(String infix){
Stack<String> stack = new Stack<>();
StringBuffer postfix = new StringBuffer(infix.length()*2);
int i = 0;
while(i<infix.length()){
char ch =infix.charAt(i);
switch (ch){
case '+':
case '-':
while (!stack.empty()&&!stack.peek().equals("(")){
postfix.append(stack.pop());//出栈,运算符添加到后缀表达式里面
}
stack.push(ch+"");//当前入栈
i++;
break;
case '/':
case '*':
while (!stack.empty()&&(stack.peek().equals('/')||stack.peek().equals('*'))){
postfix.append(stack.pop());//栈顶优先级高的运算符出栈
}
stack.push(ch+"");
i++;
break;
case '(':
stack.push(ch+"");
i++;
break;
case ')':
//出 )
while(!stack.peek().equals("(")&&!stack.isEmpty()){
postfix.append(stack.pop());
}
if(stack.peek().equals("(")){
stack.pop();
}
//出(
i++;
break;
default:
if(Character.isSpace(ch)){
i++;
break;
}
while(i<infix.length()&&ch>='0'&&ch<='9'){
postfix.append(ch);
i++;
// break;
if(i<infix.length())
ch=infix.charAt(i);
}
postfix.append(" ");//添加空格作为数值之间的分隔符
}
}
while(!stack.isEmpty()){
postfix.append((stack.pop()));
}return postfix;
}
public static void main(String[] args) {
String str = "1+(2-3)*4+10/5";
System.out.println(toPostfix(str));
}
}
输出结果
1 2 3 -4 *+10 5 /+