Demo
基于Java语言
- <span style="font-size:18px;">public class InversePoland {
- // 9+(3-1)*3+10/2 = 20
- //private static String[] ss = new String[]{"9","+","(","3","-","1",")","*","3","+","10","/","2"};
- //24+3-8*(6-3)*2+10-3
- private static String[] ss = new String[]{"24","+","3","-","8","*","(","6","-","3",")","*","2","+","10","-","3"};
- private static Stack<String> stack = new Stack<String>();
- //判断是否为数字
- private boolean isNum(String s) {
- if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("(") || s.equals(")")) {
- return false;
- }
- return true;
- }
- //获取符号优先级
- private int getPriority(String s) {
- if (s.equals("+") || s.equals("-")) {
- return 1;
- } else if (s.equals("*") || s.equals("/")) {
- return 2;
- }
- return -1;
- }
- //输出字符串
- private void print(String s) {
- System.out.print(s + " ");
- }
- //符号操作
- private void symbolOperation(String s) {
- if (stack.size() == 0 || s.equals("(")) { //栈为空,直接进栈
- stack.push(s);
- } else if (s.equals(")")) { //当前字符为“)”,则将栈中(以上的全部出栈输出
- while (stack.size() > 0) {
- String pop_s = stack.pop();
- if(pop_s.equals("(")) {
- break;
- } else {
- print(pop_s);
- }
- }
- } else {
- int pri_s = getPriority(s);
- while (stack.size() > 0 ) {
- String top_s = stack.lastElement();
- if (top_s.equals("(")) {
- stack.push(s);
- return;
- } else {
- int top_pri = getPriority(top_s);
- if (pri_s <= top_pri) {
- String pop_s = stack.pop();
- print(pop_s);
- } else {
- break;
- }
- }
- }
- stack.push(s);
- }
- }
- public void test() {
- for (String s : ss) {
- if (isNum(s)) {
- print(s);
- } else {
- symbolOperation(s);
- }
- }
- while (stack.size() > 0) {
- String pop_s = stack.pop();
- print(pop_s);
- }
- }
- }
- </span>
输出结果
24 3 + 86 3 - * 2 * - 10 + 3 –