题目描述
我们经常遇到的数学计算表达式如:(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));
}
}