計算後綴表達式的值

題目描述

我們經常遇到的數學計算表達式如:(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));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章