最近在看《大話數據結構》,看到書中介紹的逆波蘭式,想起來大學時期手寫逆波蘭式的考試題(囧,數據結構基本忘乾淨了),回顧一下,本身用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 - 數據結構