后缀表达式(逆波兰表达式)的求值

后缀表达式的求值

  • 实现思路及演示案例
  • 代码实现

实现思路及演示案例

下图所示为用栈求后缀表达式值的演示案例:
后缀表达式(逆波兰表达式)的求值_第1张图片

代码实现

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(int i = 0;i < tokens.length;i++){
            String str = tokens[i];
            if(isOperations(str) == false){//字符串步不为运算符,压栈
                int tmp = Integer.valueOf(str);
                stack.push(tmp);
            }else{//字符串为运算符,执行运算操作
                int num2 = stack.pop();//弹出栈的第一个数为右操作数
                int num1 = stack.pop();
                switch(str){
                    case "+":                    
                        stack.push(num1 + num2);
                        break;
                    case "-":
                        stack.push(num1 - num2);
                        break;
                    case "*":
                        stack.push(num1 * num2);
                        break;
                    case "/":
                        stack.push(num1 / num2);
                        break;
                }
            }
        }
        return stack.pop();
    }
    //判断是否为操作符
    private boolean isOperations(String str){
        if(str.equals("+") || str.equals("-") ||str.equals("*") ||
        str.equals("/") ){
            return true;
        }else{
            return false;
        }
    }
}

习题: 逆波兰表达式求值

你可能感兴趣的:(数据结构,java,数据结构)