import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
/**
*
*/
/**
* @author *
*/
public class PostfixEvaluator {
/**
* 将表达式分解成操作数和操作符数组
* @param string
* @return
*/
public static String[] parseExpress(String string)
{
string = string.replaceAll("\\+", " + ");
string = string.replaceAll("-", " - ");
string = string.replaceAll("\\*", " * ");
string = string.replaceAll("/", " / ");
String[] array = string.split(" ");
System.out.println(Arrays.toString(array));
return array;
}
/**
* 将中缀表达式数组转换成后缀栈
* @param infixArray
* @return
*/
public static List<String> infixToPostfix(String[] infixArray)
{
List<String> list = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
//按顺序遍历符号
for (String str : infixArray)
{
if (0 == oprLevel(str))
{
//如果是操作数,直接输出
list.add(str);
}
else if ( stack.isEmpty() || (oprLevel(str) > oprLevel(stack.peek())))
{
//如果栈为空,或符号的优先级比栈顶的符号优先级高,直接入栈
stack.push(str);
}
else
{
//如果栈不为空,并且符号优先级小于等于栈顶符号优先级,先弹出并输出栈顶符号,
//直到栈为空或符号优先级比栈顶的符号优先级高,然后再将当前符号入栈
while(!stack.isEmpty() && (oprLevel(str) <= oprLevel(stack.peek())))
{
list.add(stack.pop());
}
stack.push(str);
}
}
//所有符号都遍历了,如果栈中还有符号,弹出并输出
while (!stack.isEmpty())
{
list.add(stack.pop());
}
System.out.println(list);
//返回后缀表示输出
return list;
}
/**
* 操作数或操作符类型
* @param str
* @return 0 : 操作数
* 1 : 加减
* 2 : 乘除
*/
public static int oprLevel(String str)
{
if (str.equals("*") || str.equals("/"))
{
return 2;
}
else if (str.equals("+") || str.equals("-"))
{
return 1;
}
else
{
return 0;
}
}
/**
* 计算后缀表达式
* @param postfix
* @return
*/
public static int calculatePostfix(String[] postfix)
{
Stack<Integer> stack = new Stack<Integer>();
for (String token : postfix)
{
if ( 0 == oprLevel(token))
{
stack.push(Integer.parseInt(token));
}
else
{
int result = applyOpr(token, stack.pop(), stack.pop());
stack.push(result);
}
}
if (stack.size() != 1)
{
throw new IllegalArgumentException("后缀表达式计算错误" + Arrays.toString(postfix));
}
return stack.pop();
}
/**
* 应用操作符进行计算
* @param opr
* @param second
* @param first
* @return
*/
public static int applyOpr(String opr, int second, int first)
{
int result;
char oprChar = opr.charAt(0);
switch (oprChar) {
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
default:
throw new IllegalArgumentException("操作符'" + opr + "'错误");
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
String[] array = PostfixEvaluator.parseExpress("100+20*30-200/10");
// System.out.println("预期[100,20,30,*,+,200,10,/,-]");
List<String> list = PostfixEvaluator.infixToPostfix(array);
int result = calculatePostfix(list.toArray(new String[list.size()]));
System.out.println(result);
// String[] array2 = PostfixEvaluator.parseExpress("a+b*c-d");
// System.out.println("预期[a,b,c,*,+,d,-]");
// List<String> list2 = PostfixEvaluator.infixToPostfix(array2);
}
}