完成一个逆波兰计算器,要求完成如下任务:
1.输入一个逆波兰表达式(后缀表达式),使用栈(Stack), 计算其结果
2.支持小括号和多位数整数,因为这里我们主要讲的是数据结构,因此计算器进行简化,只3.支持对整数的计算。
代码实现
package stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
// TODO Auto-generated method stub
//先定义一个逆波兰表达式
//(3+4)x5-5 => 3 4 + 5 x 6 -
//为了方便,数字符号之间用空格隔开
String suffixExpression = "3 4 + 5 * 9 -";
//思路
//1.先将3 4 + 5 x 6 -放到ArrayList中
//2.将ArrayList传递给一个方法,遍历,配合栈,完成计算
List<String> rpnlist = getListString(suffixExpression);
System.out.println("rpblist="+rpnlist);
int res = calculate(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;
}
//完成对逆波兰表达式的运算
/*
* 从右至左扫描,将6、5、4、3压入堆栈
遇到+运算符,因此弹出3、4(3为栈顶元素、4为次栈顶元素),计算3+4的值,得到7,再将7入栈
接下来是x运算,因此弹出5 和 7,计算5x7 = 35,再将35入栈
最后是-运算符,计算出35-6的值,由此得出最终结果
*/
public static int calculate(List<String> ls) {
//创建一个栈,只需要一个栈即可
Stack<String> stack = new Stack<String>();
//遍历ls
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("运算符有误!");
}
//把res入栈
stack.push(res+"");
}
}
//最后留在stack中的数为运算结果
return Integer.parseInt(stack.pop());
}
}