集册 Java实例教程 求逆波兰表达式

求逆波兰表达式

欢马劈雪     最近更新时间:2020-01-02 10:19:05

528
计算波兰逆表达式


//package com.nowjava;
//from N o w J a v a . c o m

import java.util.List;


import java.util.Stack;


public class Main {

    public static void main(String[] argv) throws Exception {

        List inversePolandExpression = java.util.Arrays.asList("asdf",

                "nowjava.com");

        System.out

                .println(calculateInversePolandExpression(inversePolandExpression));

    }


    static private double calculateInversePolandExpression(

            List<String> inversePolandExpression) {

        double result = 0;

        Stack<Double> calculateStack = new Stack<Double>();

        for (String str : inversePolandExpression) {
        /*
        时 代 J a v a 公 众 号 - N o w J a v  a . c o m 提供
        */

            if (str.equals("+") || str.equals("-") || str.equals("*")

                    || str.equals("/")) {

                double t1 = Double.valueOf(calculateStack.pop());

                double t2 = Double.valueOf(calculateStack.pop());

                result = simpleCalculate(t2, t1, str);

                calculateStack.push(result);

            } else {

                calculateStack.push(Double.valueOf(str));

            }

        }


        return result;

    }


    static private double simpleCalculate(double x, double y, String sign) {

        double result = 0;

        if (sign.equals("+")) {

            result = x + y;

        } else 
展开阅读全文