波兰表达式(前序表达式)的计算(栈)

波兰表达式是一种命题逻辑的特殊表示法,允许从公式中删除所有的符号。

例如中序表达式转换为前序表达式(波兰表达式):

        (2-3)*(4+5) = * - 2 3  + 4 5

这里通过使用栈的方式来计算波兰表达式

原理:

    从表达式的尾开始遍历,遇到数值则压栈。

    遇到操作符则出栈两次获得操作数,其中第一次出栈的数作为被操作数,第二次出栈的数作为操作数  ,计算这一次的子表达式的值,然后将结果压栈。


实现代码:

      public static Double PolanCaculate(String expression)
	  {
		  String exarr[] = expression.split(" "); 
		  Stack stack=new Stack<Float>();
		  for(int i = exarr.length - 1; i>=0; i--)
		  {
			  
			  if(exarr[i] == " " || exarr[i].equals(" ")) continue;
			
			  if(exarr[i].equals("+"))
				  stack.push((Double)stack.pop()+(Double)stack.pop());
			  else if(exarr[i].equals("-"))
				  stack.push((Double)stack.pop()-(Double)stack.pop());
			  else if(exarr[i].equals("*"))
				  stack.push((Double)stack.pop()*(Double)stack.pop());
			  else if(exarr[i].equals("/"))
				  stack.push((Double)stack.pop()/(Double)stack.pop());
			  else
				  stack.push(Double.parseDouble(exarr[i]));
		  }
		  return (Double)stack.pop();
	  }

猜你喜欢

转载自blog.csdn.net/qq_30268545/article/details/80620466