@hainingwyx
2017-07-23T14:40:30.000000Z
字数 953
阅读 1448
数据结构
20世纪50年代,波兰逻辑学家提出了一种不需要括号的后缀表示法,也成为逆波兰(Reverse Polish Notatiojn ,RPN)表示。
后缀表达式:所有的符号都要在要运算的数字的后面出现。例如:“9+(3-1)x3+10/2”后缀表达式为:“9 3 1 - 3 * + 10 2 / +”
对于“9 3 1 - 3 * + 10 2 / +”为例:
import java.util.Stack;public class RPN {public static int evalRPN(String[] tokens) {Stack<Integer> stack = new Stack<Integer>();for(int i = 0;i<tokens.length;i++){try{int num = Integer.parseInt(tokens[i]);stack.add(num);}catch (Exception e) {int b = stack.pop();int a = stack.pop();stack.add(get(a, b, tokens[i]));}}return stack.pop();}private static int get(int a,int b,String operator){switch (operator) {case "+":return a+b;case "-":return a-b;case "*":return a*b;case "/":return a/b;default:return 0;}}public static void main(String[] args) {String[] strlist = {"2", "1", "+", "3", "*"};System.out.println(evalRPN(strlist));}}
