package Stack;import java.io.*;public class infixApp {public static void main(String[] args) throws IOException {String input,output;while(true) {System.out.println("输入:");System.out.flush();input = getString();if(input.equals(""))break;IntoPost theTrans = new IntoPost(input);output = theTrans.doTrans();System.out.print("Postfix is"+output+"\n");}}public static String getString() throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String s = br.readLine();return s;}}class IntoPost{private Stack stack;private String input;private String output="";public IntoPost(String in) {this.input = in;int stackSize = this.input.length();this.stack = new Stack(stackSize);}public String doTrans() {for(int i=0;i<this.input.length();i++) {char ch = this.input.charAt(i);this.stack.display("For "+ch+" ");switch(ch) {case '+':case '-':this.gotOper(ch,1);break;case '*':case '/':this.gotOper(ch,2);break;case '(':this.stack.push(ch);break;case ')':this.gotParen(ch);break;default:this.output = output + ch;break;}}while(!this.stack.isEmpty()) {this.stack.display("While ");this.output = this.output + this.stack.pop();}this.stack.display("End ");return this.output;}public void gotOper(char opThis, int prec1) {while(!this.stack.isEmpty()) {char opTop = this.stack.pop();if(opTop=='(') {this.stack.push(opTop);break;}else {int prec2;if(opTop=='+' || opTop=='-') {prec2 = 1;}else {prec2 = 2;}if(prec2 < prec1) {this.stack.push(opTop);break;}else {this.output = this.output+opTop;}}}this.stack.push(opThis);}public void gotParen(char ch) {while(!this.stack.isEmpty()) {char chx = this.stack.pop();if(chx =='(') {break;}else {this.output = this.output+chx;}}}}class Stack {private char[] a;private int maxsize;private int top;public Stack(int s) {this.maxsize = s;this.a = new char[this.maxsize];this.top = -1;}//入栈public void push(char value) {this.a[++this.top] = value;}//出栈public char pop() {return this.a[this.top--];}//查看public char peek() {return this.a[this.top];}public char peekN(int n) {return this.a[n];}//是否为空public boolean isEmpty() {return (this.top == -1);}//是否已满public boolean isFull() {return (this.top == this.maxsize-1);}public int size() {return this.top-1;}public void display(String s) {System.out.println(s);System.out.println("Stack (bottom->top)");for(int j=0;j<this.size();j++) {System.out.print(this.peekN(j));System.out.print("");}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。