最近在看《大话数据结构》,看到书中介绍的逆波兰式,想起来大学时期手写逆波兰式的考试题(囧,数据结构基本忘干净了),回顾一下,本身用java写了一个比较拙劣的逆波兰式算法,当练手吧。
java
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); } } }
输出结果算法
24 3 + 8 6 3 - * 2 * - 10 + 3 - 数据结构