標籤:資料結構 計算機 棧
原理:
1.將中序運算式變化後續運算式
2.當前字元為數字,將該數字放入棧中
3.當前字元為操作符,從棧中取出兩個樹,根據操作符來運算,將運算結果放入到棧中
4.重複,直到將字元操作完,此時棧中只剩下一個元素,即要運算的結果
PS:我沒有處理,只可以運行10以內的運算,如果有需要可以擴充
package com.lip.datastructure.tree;import java.util.Iterator;import java.util.Stack;public class Calculator{public static void main(String[] args){String obj = "a*(b+c)+c/d";String obj1 = "2*(1+3)+9/3";System.out.println(obj1+"="+calculator(obj1));}//利用後序運算式計算///原理:1.當期字元為字母或者數字,則直接入棧// 2.當前字元為操作符則從棧中取出兩個數字計算// 3.將計算結果再放入到棧中,棧中最後剩餘的一個元素就是要求的結果public static int calculator(String obj){String postObj=tranform(obj);System.out.println();Stack<Integer>stack=new Stack<Integer>();for(int i=0;i<postObj.length();i++){char ch=postObj.charAt(i);if(Character.isLetterOrDigit(ch))//字元或者數字{stack.push(Integer.parseInt(ch+""));}else//操作符{//取出兩個數int op1,op2;op1=stack.pop();op2=stack.pop();switch (ch){case '+':stack.push(op2+op1);break;case '-':stack.push(op2-op1);break;case '*':stack.push(op2*op1);break;case '/':stack.push(op2/op1);break;default:break;}}}return stack.pop();}// 中序遍曆改為後續遍曆public static String tranform(String obj){Stack<Character> stack = new Stack<Character>();String obj2 = "";for (int i = 0; i < obj.length(); i++){char ch = obj.charAt(i);if (Character.isLetterOrDigit(ch))// 字母或數字直接輸出{obj2 += ch;System.out.print(ch);} else if (ch == ')')// 在棧中一致匹配到)操作符才停止出棧{char temp;while ((temp = stack.pop()) != '('){obj2 += temp;System.out.print(temp);}} else// 比較操作符的進棧優先順序{if (stack.isEmpty()){stack.push(ch);continue;}char temp = stack.peek();while (icp(ch) <= isp(temp))// 進棧優先順序小於棧內優先順序,則一直出棧{System.out.print(temp);obj2 += temp;stack.pop();if (stack.isEmpty())break;temp = stack.peek();}stack.push(ch);}}// 將棧中剩餘的元素彈出來while (!stack.isEmpty()){char temp = stack.pop();obj2 += temp;System.out.print(temp);}return obj2;}// 操作符在棧內的優先順序private static int isp(char ch){switch (ch){case '+':case '-':return 2;case '*':case '/':return 4;case ')':return 7;case '(':return 1;default:break;}return 0;}// 操作符進棧的優先順序優先順序private static int icp(char ch){switch (ch){case '+':case '-':return 3;case '*':case '/':return 5;case ')':return 1;case '(':return 7;default:break;}return 0;}}
資料結構之計算機的實現(JAVA)(四)