calculate Inverse Poland Expression - Java Data Structure

Java examples for Data Structure:Inverse Poland Expression

Description

calculate Inverse Poland Expression

Demo Code


//package com.java2s;

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",
                "java2s.com");
        System.out//from  w  w w  .jav a 2 s.  com
                .println(calculateInversePolandExpression(inversePolandExpression));
    }

    static private double calculateInversePolandExpression(
            List<String> inversePolandExpression) {
        double result = 0;
        Stack<Double> calculateStack = new Stack<Double>();
        for (String str : inversePolandExpression) {
            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 if (sign.equals("-")) {
            result = x - y;
        } else if (sign.equals("*")) {
            result = x * y;
        } else if (sign.equals("/")) {
            result = x / y;
        }
        return result;

    }
}

Related Tutorials