中綴表示式轉字尾表示式的簡單實現
阿新 • • 發佈:2020-09-19
分析步驟:
實現程式碼:
package com.cai.learn.math; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * 目標中綴表示式轉成字尾表示式 */ public class InfixToSuffixTest { public static void main(String[] args) { //表示式 1 + ( ( 2 * 3) - 5 ) + 8 String infix = "1 + ( ( 2 * 3 ) - 5 ) + 8"; //-->[1, 2, 3, *, 5, -, +, 8] 1 2 3 * 5 - + 8 + =10 Stack<String> stackOperate = new Stack<String>(); //符號棧 List<String> list = new ArrayList<String>(); //相當於中間儲存 String[] arr = infix.split(" "); for (int i = 0; i < arr.length; i++) { String str= arr[i]; if(str.matches("\\d+")){ list.add(str); }else{ if(stackOperate.empty()||"(".equals(str)){ stackOperate.push(str); }else if(")".equals(str)){ while(!"(".equals(stackOperate.peek())){ list.add(stackOperate.pop()); } stackOperate.pop(); }else if(Priority.getPriority(str)>Priority.getPriority(stackOperate.peek())){ stackOperate.push(str); }else{ while(true){ if(stackOperate.empty())break; String thisOperate = stackOperate.peek(); if("(".equals(thisOperate))break; if(Priority.getPriority(str)>Priority.getPriority(thisOperate))break; list.add(stackOperate.pop()); } stackOperate.push(str); } } } while (!stackOperate.empty()){ list.add(stackOperate.pop()); } System.out.println(list); } } class Priority{ private static final int ADD = 1; private static final int SUB = 1; private static final int MUL = 2; private static final int DIV = 2; public static int getPriority(String operate){ if("+".equals(operate)) return ADD; else if("-".equals(operate)) return SUB; else if("*".equals(operate)) return MUL; else if("/".equals(operate)) return DIV; else return 0; } }