队列-解析算数表达式:后缀表达式

来源:互联网 发布:虚拟充值软件靠谱吗 编辑:程序博客网 时间:2024/06/07 04:00
package d_queue.D_SuffixExpression;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 * 解析算数表达式:后缀表达式
 * @author Administrator
 *
 */
public class InfixApp {
public static void main(String[] args) throws IOException {
String input, output;
while (true) {
System.out.print("Enter infix:");
System.out.flush();
input=getString();
if(input.equals(""))break;
IntoPost theIntoPost=new IntoPost(input);
output=theIntoPost.doTrans();
System.out.println("Postfix is "+output);
}
}


public static String getString() throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in))
.readLine();
return s;
}
}package d_queue.D_SuffixExpression;


public class IntoPost {// infix to postfix conversion 中缀转后缀转换
private StackX theStackX;
private String input;
private String output = "";


public IntoPost(String in) {
input = in;
theStackX = new StackX(input.length());
}


public String doTrans() {// do translation to postfix 转变后缀
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
theStackX.displaysStack("For:"+ch);
switch (ch) {
case '+':
case '-':
gotOper(ch,1);
break;
case '*':
case '/':
gotOper(ch,2);
break;
case '(':
theStackX.push(ch);
break;
case ')':
gotParen(ch);
break;
default:
output=output+ch;
break;
}
}
//从栈中弹出剩下的操作符
while(!theStackX.isEmpty()){
theStackX.displaysStack("While ");
output=output+theStackX.pop();
}
theStackX.displaysStack("End ");
return output;
}


private void gotOper(char opThis, int prec1) {
while (!theStackX.isEmpty()) {
char opTop = theStackX.pop();//因为要和前面的数据项比较优先级,所以要拿出来
if (opTop == '(') {
theStackX.push(opTop);
break;
} else {
int prec2;
if (opTop == '+' || opTop == '-') {
prec2 = 1;
} else {
prec2 = 2;
}
if (prec2 < prec1) {
theStackX.push(opTop);
break;
} else {
output = output + opTop;
}


}
}
theStackX.push(opThis);
}


private void gotParen(char ch) {
while(!theStackX.isEmpty()){
char chx=theStackX.pop();
if(chx=='('){
break;
}else{
output=output+chx;
}
}
}


}package d_queue.D_SuffixExpression;


public class StackX {
private int maxSize;
private char[] stackArray;
private int top;


public StackX(int s) {
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}


public void push(char c) {
stackArray[++top] = c;
}


public char pop() {
return stackArray[top--];
}


public char peek() {
return stackArray[top];
}


public boolean isEmpty() {
return top == -1;
}


public int size() {
return top + 1;
}


public char peekN(int n) {
return stackArray[n];
}


/*
* 显示堆栈
*/
public void displaysStack(String s) {
System.out.print(s);
System.out.print(" Stack {bottom-->top}:");
for (int j = 0; j < size(); j++) {
System.out.print(peekN(j));
System.out.print(" ");
}
System.out.println();
}
}
0 0