逆波兰计算器的实现
- 输入一个逆波兰表达式(后缀表达式), 使用栈(Stack), 计算其结果
- 支持小括号和多位数整数, 因为这里我们主要针对于数据结构, 因此计算器进行简化, 只支持对整数的计算
- 思路分析
- 代码完成
package com.beyond.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
String suffixExpression = "3 4 + 5 * 6 -";
List<String> rpnList = getListString(suffixExpression);
System.out.println(rpnList);
System.out.println(calculate(rpnList));
}
public static List<String> getListString(String suffixExpression){
String split [] = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for(String ele: split) {
list.add(ele);
}
return list;
}
public static int calculate(List<String> ls) {
Stack<String> stack = new Stack<String>();
for(String item: ls) {
if (item.matches("\\d+")) {
stack.push(item);
}else {
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(String.valueOf(res));
}
}
return Integer.parseInt(stack.pop());
}
}