计算后缀表达式的值

题目描述

我们经常遇到的数学计算表达式如:(2+1)*3,成为中缀表达式,这种表达式对于我们来说很容易理解,但是计算机容易理解的形式却是后缀表达式,即,将运算符写在两个运算符的后面,如上述中缀表达式的后缀表达式为:21+3*。计算机计算后缀表达式的过程为,从左到右,遍历表达式,如果当前位是数字,那么先将其暂存,继续往后遍历;如果碰到运算符,那么就取出最近暂存的两个数字,并计算出值,然后将该值继续暂存,直到遍历结束,此时输出暂存区的数字即可。

说明:其中后缀表达式的开头存储在栈顶,后缀表达式的最后一位存储在栈底。

Java代码如下

/**
 * Main_HouZui
 * 中缀表达式为 (2+3)*5/25
 * 计算后缀表达式的值,23+5*25/
 */
import java.util.Stack;
public class Main_HouZui 
{

    public static int calculate (int first, int second, String operator)
    {
        int result = 0;
        switch(operator)
        {
            case "+":
                result = first + second;
                break;
            case "-":
                result = first - second;
                break;
            case "*":
                result = first * second;
                break;
            case "/":
                result = first/second;
                break;
        }
        return result;
    }
    //stack栈中存放的是后缀表达式 23+5*25/
    public static int function(Stack<String> stack)
    {
        // 碰到运算符,那么就取出最近暂存的两个数字,并计算出值,然后将该值继续暂存到result
        Stack<Integer> result = new Stack<Integer>();
        while(!stack.isEmpty())
        {
            String element = stack.pop();//取栈顶元素
            try
            {
                //将String 的 1 转为 Integer,遇到 String "+"则有异常了,转到catch语句
                result.push(Integer.valueOf(element));
            }
            catch(Exception e)
            {
                int b = result.pop();
                int a = result.pop();
                result.push(calculate(a, b, element));
            }
        }
        return result.pop();
    }
    public static void main(String[] args) 
    {
        Stack<String> s = new Stack<>();
        s.push("/");
        s.push("25");
        s.push("*");
        s.push("5");
        s.push("+");
        s.push("3");
        s.push("2");

        System.out.println(function(s));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值