資料結構之計算機的實現(JAVA)(四)

來源:互聯網
上載者:User

標籤:資料結構   計算機 棧   

   原理:

       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)(四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.