[Java数据结构][6]逆波兰表达式的Java代码实现
逆波兰表达式又叫做 后缀表达式。逆波兰表示法是波兰逻辑学家J・卢卡西维兹(J・ Lukasewicz)于1929年首先提出的一种表达式的表示方法 。后来,人们就把用这种表示法写出的表达式称作“逆波兰表达式”。逆波兰表达式把运算量写在前面,把算符写在后面。
如(3+4)×5-6,写作逆波兰表达式就是3 4 + 5 × 6
规则
1.从左至右扫描,将3 和4 压入堆栈;
2.遇到+运算符,因此弹出4 和3(4 为栈顶元素,3 为次顶元素),计算出3+4 的值,得7,再将7 入栈;
3.将5 入栈;
4.接下来是×运算符,因此弹出5 和7,计算出7×5=35,将35 入栈;
5.将6 入栈;
6.最后是-运算符,计算出35-6 的值,即29,由此得出最终结果
完整代码(含有详细注释)
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//定义一个逆波兰表达式
// (3+4)*5-6 -> 3 4 + 5 * 6 -
String suffixExpression = "3 4 + 5 * 6 -";
List<String> rpnList = getListString(suffixExpression);
System.out.println("rpnList = " + rpnList);
int res = caculate(rpnList);
System.out.println("计算的结果是:" + res);
}
/**
* 将一个逆波兰表达式,依次将数据和运算符 放入到ArrayList中
*/
public static List<String> getListString(String suffixExpression) {
//将suffixExpression分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String ele : split) {
list.add(ele);
}
return list;
}
/**
* 完成逆波兰表达式的运算
*/
public static int caculate(List<String> ls) {
//只需一个栈
Stack<String> stack = new Stack<String>();
//遍历List
for (String item : ls) {
//正则表达式
if (item.matches("\\d+")) { //匹配的是多位数
stack.push(item);
} else {
// pop出两个数,并运算再入栈
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if (item.equals("+")) {
res = num1 + num2;
} else if (item.equals("-")) {
res = num1 - num2;
} else if (item.equals("*")) {
res = num1 * num2;
} else if (item.equals("/")) {
res = num1 / num2;
} else {
throw new RuntimeException("运算符有误!");
}
stack.push("" + res);
}
}
return Integer.parseInt(stack.pop());
}
}