1.创建一个栈的类,里面包括一般的对象
public class StackX {
private int maxSize;
private char [] stackArray;
private int top;
public StackX(int max){
maxSize=max;
stackArray=new char[maxSize];
top=-1;
}
public void push(char j){
stackArray[++top]=j;
}
public char pop(){
return stackArray[top--];
}
//return item at index n
public char peakN(int n){
return stackArray[n];
}
public char peek(){
return stackArray[top];
}
public boolean isEmpty(){
return (top==-1);
}
public void displayStack(String s){
System.out.println("Stack(bottom-->top):");
for(int j=0;j<size();j++){
System.out.println(peakN(j));
System.out.print(' ');
}
System.out.println("");
}
public int size(){
return top+1;
}
public boolean isFull(){
return(top==maxSize-1);
}
}
2.新建一个转换的类,类里面包括表达式转换的对象
其中的转换过程是:首先如果遇到的是操作数直接输出就行,如果遇到操作符将其压入栈中比如 A*(B+C)-D/(E+F)
先输出A,然后是*,直接压入栈中,紧接着( 也压入栈中, 将 B输出 判断+与栈顶元素的优先级 ,因为此时栈顶元素为(,所以将+号压入栈中,C输出,后面检测到 ),开始出栈操作,即ABC+*,后部分与前面类似,即可得出最后的后缀表达式为ABC+*DEF+/-
public class InToPost {
private StackX theStack;
private String input;
private String output="";
public InToPost(String in) {
input = in;
int stackSixe = input.length();
theStack = new StackX(stackSixe);
}
public String doTrans(){
for(int j=0;j<input.length();j++){
char ch=input.charAt(j);//选取指定位置的字符
theStack.displayStack("For"+ch+" ");
switch(ch){
case '+':
case '-':
gotOper(ch,1);
break;
case '*':
case '/':
gotOper(ch,2);
break;
case '(':
theStack.push(ch);
break;
case ')':
gotParen(ch);
break;
default:
output=output+ch;
break;
}
}
while(!theStack.isEmpty()){
theStack.displayStack("While");
output=output+theStack.pop();
}
theStack.displayStack("End ");
return output;
}
public void gotOper(char opThis,int prec1){
while(!theStack.isEmpty()){
char opTop=theStack.pop();
if(opTop=='('){
theStack.push(opTop);
break;
}
else{
int prec2;
if(opTop=='+'||opTop=='-')
prec2=1;
else
prec2=2;
if(prec2<prec1){
theStack.push(opTop);
break;
}
else
output=output+opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch){
while(!theStack.isEmpty()){
char chx=theStack.pop();
if(chx=='(')
break;
else
output=output+chx;
}
}
}
3.主类
import java.io.*;
public class InfixApp {
public static void main(String[] args) throws IOException {
String input,output;
while(true){
System.out.println("Enter infix");
System.out.flush();
input=getString();
if(input.equals(""))
break;
InToPost theTrans=new InToPost(input);
output=theTrans .doTrans();
System.out.println("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;
}
}