表示式求值-中序表示式轉換成後序表示式然後求值
阿新 • • 發佈:2018-11-09
/*表示式求值,先轉換成字尾表示式,再計算。 //從中綴表示式中從左往右依次取出資料 //如遇到運算元,直接輸出到字尾的佇列裡。 //如果遇到操作符(包括括號),這裡再定義一個存放操作符的棧,則: //i.如果操作符是'(',入棧 //ii.如果操作符是')',則把棧裡的操作符依次出棧並插入到字尾序列後面,直到遇到')'. //iii.如果操作符不是‘(’和‘)’,則: // (1). 如果操作符的優先順序比top的優先順序高,則入棧 // (2).如果操作符優先順序等於或小於top優先順序,則將top出棧並插入到字尾序列後面,pop後,再比較棧頂元素的優先順序,重複iii,直到把此操作符 插入,將此操作符入棧。 如果中序佇列裡的資料已經讀取完畢,記錄操作符的棧裡,還有操作符的話,依次出棧插入到字尾序列的後面。 此時中綴就已經轉換為字尾表示式。*/ //然後對字尾表示式從前到後掃描,遇到資料入棧,遇到操作符則彈出兩個數字進行計算,然後將計算結果入棧,重複操作,當掃描完畢後,棧定的元素便是結果 import java.util.*; public class Biaodashi1 { public static void main(String args[]){ Scanner in=new Scanner(System.in); while(in.hasNext()){ String str=in.nextLine(); System.out.printf("%.0f\n",f2(str)); } } public static double f2(String str){ Stack<String> stack=new Stack<String>(); Queue<String> queue=new LinkedList<String>(); String str1[]=str.split(" "); for(int i=0;i<str1.length;i++){ if(str1[i].compareTo("*")==0 || str1[i].compareTo("/")==0){ while(stack.size()>0){ String temp2=stack.peek(); if(temp2.compareTo("*")==0 ||temp2.compareTo("/")==0){ queue.offer(stack.pop()); }else{ break; } } stack.push(str1[i]); }else if(str1[i].compareTo("+")==0 || str1[i].compareTo("-")==0){ while(stack.size()>0){ String temp2=stack.peek(); if(temp2.compareTo("*")==0 ||temp2.compareTo("/")==0 ||temp2.compareTo("+")==0 ||temp2.compareTo("-")==0){ queue.offer(stack.pop()); }else{ break; } } stack.push(str1[i]); }else if(str1[i].compareTo("(")==0){ stack.push(str1[i]); }else if(str1[i].compareTo(")")==0){ String temp1=stack.pop(); while(temp1.compareTo("(")!=0){ queue.offer(temp1); temp1=stack.pop(); } }else{ queue.offer(str1[i]); } } while(stack.size()>0){ queue.offer(stack.pop()); } Stack<String> res=new Stack<String>(); while(queue.size()>0){ String temp3=queue.poll(); if(temp3.compareTo("+")==0 || temp3.compareTo("-")==0 || temp3.compareTo("*")==0 || temp3.compareTo("/")==0){ double num1=Double.parseDouble(res.pop()); double num2=Double.parseDouble(res.pop()); if(temp3.compareTo("+")==0){ res.push((num1+num2)+""); }else if(temp3.compareTo("-")==0){ res.push((num2-num1)+""); }else if(temp3.compareTo("*")==0){ res.push((num2*num1)+""); }else{ res.push((num2/num1)+""); } }else{ res.push(temp3); } } return Double.parseDouble(res.pop()); } }