一、后缀表达式 (逆波兰表达式)
后缀表达式又称逆波兰表达式。运算符位于操作数之前。
比如:(3+2)*6-5 对应后缀表达式就是:3 2 + 6 * 5 -
在实际开发中,常常是将中缀表达式转为后缀表达式,因为后缀表达式相对于其他表达式来说对计算机较为友好。
. 思路分析
计算机从左至右扫描表达式,遇到数字直接入栈,遇到运算符,弹出栈顶和次顶的两个数进行运算,最后将运算结果入栈,重复操作,直到表达式最后。最终返回运算结果。
简单示例:
3 2 + 6 * 5 -
- 遇3,入栈
- 遇2,入栈
- 遇+,弹出栈顶和次顶两数,3和2进行运算,即3+2=5,5入栈
- 遇6,入栈
- 遇*,弹出栈顶和次顶两数,6和5进行运算,即6*5=30,30入栈
- 遇5,入栈
- 遇-,弹出栈顶和次顶两数,5和30进行运算,即30-5=25,25入栈。(注意:遇到减法和除法,先出栈的为被减数或被除数)
- 得到最终结果25
. 代码实现 逆波兰计算器
重点在于数据结构,不支持小数点的运算。
public class SuffixCalculator {
public static void main(String[] args) {
// 计算(3+20)*6-5 转为后缀表达式 3 20 + 6 * 5 -
String suffixExpression = "3 20 + 6 * 5 -";
String[] rpnExpression = suffixExpression.split(" ");
int result = calculator(rpnExpression);
System.out.println("计算结果为:"+result);
}
public static int calculator(String[] rpn){
int res = 0;
Stack<String> stack = new Stack<>();
// 遍历数组
for (String item : rpn) {
// 如果为数字直接入栈,如果为运算符,直接取出栈中元素进行运算
if(item.matches("\\d+")){
stack.push(item);
}else {
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
switch (item){
case "+":
res = num1 + num2;
break;
case "-":
res = num2 - num1; // 注意先出栈为被减数
break;
case "*":
res = num1 * num2;
break;
case "/":
res = num2 / num1; // 注意先出栈为被除数
break;
default:
throw new RuntimeException("运算符有误...");
}
stack.push(String.valueOf(res));
}
}
return Integer.parseInt(stack.pop());
}
}
计算结果为:133
二、表达式转换
. 中缀转后缀表达式
人工转:
(3+2)*6-5
根据优先级将所有运算符都加上括号,原本的括号不动;根据优先级将符号移到括号后面;最后去掉括号即可
(((3+2)*6)-5)
(((3+2)6)*-5)
(((32)+6)*-5)
(((32)+6)*5)-
3 2 + 6 * 5 -
. 思路分析
- 设计两个栈,一个运算符栈s1,一个存储中间结果的栈s2
- 将中缀表达式从左至右依次扫描
- 遇到数字,直接入栈到中间结果栈s2
- 遇到运算符:
- 如果s1栈是空的直接入栈,如果栈顶符号为左括号"(",也直接入栈
- 否则,如果入栈的运算符优先级高于栈顶运算符,也直接入栈s1
- 否则,将s1中栈顶的运算符弹出压入s2中,再回到4.1步骤判断新栈顶运算符的优先级别
- 遇到括号:
- 如果是左括号"(",直接入栈s1
- 如果是右括号")",依次将s1中栈顶的运算符压入s2,直到遇见左括号"("停止,此时这一对括号丢弃无用。
- 重复2~5的操作,直到扫描完成
- 最后将s1中的运算符依次弹出,入栈s2
- 此时将s2的元素依次弹出的逆序就是中缀表达式的后缀表达式了
tips:
有没有发现,s2这个栈的作用是一直是入栈的操作,只有最后才将s2的元素弹出来反转,其实直接用一个list集合代替s2这个栈也可以完成最终操作,并且更加方便。
简单示例:
1 + ( ( 2 + 3 ) * 4 ) - 5
. 代码实现
没考虑小数
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class InfixToSuffix {
public static void main(String[] args) {
String infixExpression = "15+((120+6)*2)-5";
// 将中缀表达式转换成list集合存储,方便对数据遍历和操作
List<String> infixListExpression = toInfixListExpression(infixExpression);
// 根据中缀转后缀规则进行转换
Stack<String> operStack = new Stack<>(); // 符号栈
List<String> suffixExpression = new ArrayList<>(); // 存储后缀表达式
// 遍历list集合中的每一个元素
for(String item : infixListExpression){
if(item.matches("\\d+")){ // 如果为数字,直接加入到suffixExpression中
suffixExpression.add(item);
}else if (item.equals("(")){ // 如果为左括号,直接加入到suffixExpression中
operStack.push(item);
}else if (item.equals(")")){ // 如果为右括号,将左括号之前的符号都加入到suffixExpression中
if(!operStack.peek().equals("(")){
suffixExpression.add(operStack.pop());
}
operStack.pop(); // 遇到左括号后,将其pop出
}else if (!operStack.empty() && operStack.peek().equals("(")){
// 如果栈不为空,并且栈顶是左括号,运算符号直接入栈
operStack.push(item);
}else {
while (true){
// 如果符号栈不为空,并且栈顶不是左括号,就比较运算符优先级,
// 如果小于等于栈顶优先级,就将符号取出,再次判断栈是否为空,
// 新的栈顶是否为左括号
if(!operStack.empty()){
if (operStack.peek().equals("(")){
break;
}else if(operationPriority(item) <= operationPriority(operStack.peek()) ){
suffixExpression.add(operStack.pop());
}else {
break;
}
}else {
break;
}
}
operStack.push(item);
}
}
// 将栈中剩下的符号依次取出,并加入到suffixExpression中
while (true){
if(!operStack.empty()){
suffixExpression.add(operStack.pop());
}else {
break;
}
}
System.out.println("中缀表达式:"+infixExpression);
System.out.println("后缀表达式:"+suffixExpression);
}
public static List<String> toInfixListExpression(String infix){
List<String> list = new ArrayList<>();
int index = 0;
String val = "";
while (index < infix.length()){
val = infix.substring(index,index+1);
// 如果num是数字,那么就判断下一位是否还是数字,是就继续追加,不是就退出
while (val.matches("\\d+") && index+1 < infix.length()){
if(infix.substring(index+1,index+2).matches("\\d+")){
val += infix.substring(index+1,index+2);
index++;
}else {
break;
}
}
list.add(val);
index++;
}
return list;
}
public static int operationPriority(String oper){
int result;
switch (oper){
case "+":
case "-":
result = 1;
break;
case "*":
case "/":
result = 2;
break;
default:
throw new RuntimeException("运算符有误...");
}
return result;
}
}
中缀表达式:15+((120+6)*2)-5
后缀表达式:[15, 120, 6, +, 2, *, +, 5, -]