大話資料結構——使用棧實現簡單的四則運算,資料結構四則運算

來源:互聯網
上載者:User

大話資料結構——使用棧實現簡單的四則運算,資料結構四則運算

最近在讀《大話資料結構》,裡面有個例子是使用棧實現四則運算,現在我用java把這個功能實現試試

代碼如下:

package com.datastruct;import java.util.ArrayList;import java.util.Stack;import java.util.regex.Matcher;import java.util.regex.Pattern;public class StackPractice {private static ArrayList<String> symbolList;static{symbolList = new ArrayList<>();symbolList.add(SymbolEnum.ADD.getVal());symbolList.add(SymbolEnum.SUBTRACT.getVal());symbolList.add(SymbolEnum.MULTIPLY.getVal());symbolList.add(SymbolEnum.DIVIDE.getVal());symbolList.add(SymbolEnum.LEFT_BRACKET.getVal());symbolList.add(SymbolEnum.RIGHT_BRACKET.getVal());}public static void main(String[] args) {String exp = "9+(3-1)*3+10/2";try {String exp2 = convertExp(exp);System.out.println(cal(exp2));} catch (Exception e) {System.out.println(e.getMessage());}}private static boolean isNumeric(String str){    Pattern pattern = Pattern.compile("[0-9]*");    Matcher isNum = pattern.matcher(str);   if( !isNum.matches() ){       return false;    }    return true; }/** * 計算尾碼運算式值 * @return */private static int cal(String exp){String[] expArr = exp.split(" ");Stack<String> calStack = new Stack<String>();for(int i=0;i<expArr.length;i++){String tmp = expArr[i];if(isNumeric(tmp)){//數字入棧calStack.push(tmp);}else{int num1 = Integer.parseInt(calStack.pop());//棧頂彈出1int num2 = Integer.parseInt(calStack.pop());//棧頂彈出2switch (tmp) {case "-":calStack.push(num2 - num1 + "");break;case "+":calStack.push(num2 + num1 + "");break;case "*":calStack.push(num2 * num1 + "");break;case "/":calStack.push(num2 / num1 + "");break;default:break;}}}return Integer.parseInt(calStack.pop());}/** * 中綴運算式轉為尾碼運算式 * @return */private static String convertExp(String exp) throws Exception{//字串轉數組char[] expArr = exp.toCharArray();StringBuffer sb = new StringBuffer();Stack<String> symbolStack = new Stack<>();boolean isLastCharNumberFlag = true;for(int i = 0;i<expArr.length;i++){char curChar = expArr[i];//若為數字添加 若為符號則放入棧計算if(Character.isDigit(curChar)){if(isLastCharNumberFlag){sb.append(curChar);}else{sb.append(" ").append(curChar);}isLastCharNumberFlag = true;}else if(symbolList.contains(String.valueOf(curChar))){//符號//String symbol = String.valueOf(curChar);if(SymbolEnum.RIGHT_BRACKET.getVal().equals(symbol) ){//如果是右括弧,得匹配左括弧 String symbolStr = symbolStack.pop();while(!SymbolEnum.LEFT_BRACKET.getVal().equals(symbolStr)){sb.append(" ").append(symbolStr);symbolStr = symbolStack.pop();}isLastCharNumberFlag = false;continue;}else if(SymbolEnum.DIVIDE.getVal().equals(symbol) ||SymbolEnum.MULTIPLY.getVal().equals(symbol)){}else{if(symbolStack.isEmpty()){symbolStack.push(symbol);continue;}String symbolStr = symbolStack.peek();if(SymbolEnum.DIVIDE.getVal().equals(symbolStr) ||SymbolEnum.MULTIPLY.getVal().equals(symbolStr)){while(!symbolStack.isEmpty()){sb.append(" ").append(symbolStack.pop());}symbolStack.push(symbol);isLastCharNumberFlag = false;continue;}}symbolStack.push(symbol);isLastCharNumberFlag = false;}}while(!symbolStack.isEmpty()){sb.append(" ").append(symbolStack.pop());}return sb.toString();}/** * 運算子枚舉 * @author Administrator * */enum SymbolEnum{ADD("+"), SUBTRACT("-"),MULTIPLY("*"),DIVIDE("/"),LEFT_BRACKET("("),RIGHT_BRACKET(")");private String val;public String getVal(){return val;}private SymbolEnum(String val){this.val = val;}}}

  程式暫時有些bug,如運算式合法性沒有校正,不能輸入多個括弧等

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.