2017年7月29日 星期六

(JAVA)(資料結構)中序式轉前序式(轉回中序式)

/*
 * 
 * 中序式轉前序式
 * 
 * 
 */
public class InFixToPrefix {
static int priority(char op){ //順序   *,/ > +,- 
if(op == '+' || op == '-')
return 1 ;
else if(op == '*' || op == '/')
return 2 ;
else
return 0 ;
}
public static void main(String[] args) {
String infix = "(A+B)*D+E/(F+A*D)+C";
//a+b*d+c/d , (A+B)*D+E/(F+A*D)+C
System.out.println("前序式為 :" +ToPrefix(infix.toCharArray()));
String Prefix = ToPrefix(infix.toCharArray());
System.out.println("中序式為 :" +ToInFix(Prefix.toCharArray()));
}
static String ToPrefix(char[] infix){
char[] stack = new char[infix.length]; //堆疊
StringBuffer Posfix = new StringBuffer(); //輸出:前序式
char[] Infix = infix;

int top =   0; 
for(int i = Infix.length - 1; i >= 0; i--){
if(Infix[i] == '+'|| Infix[i] == '-'||Infix[i] == '*' || Infix[i] == '/'){
while( priority(stack[top]) >  priority(Infix[i])){
Posfix.append(stack[top]);
top--;
}
if(top  <  stack.length){
       top++ ;
   stack[top] = Infix[i];
   }

}else if(Infix[i] == ')'){
if(top  <  stack.length ){
   top++ ;
stack[top] = Infix[i];
}
}else if(Infix[i] == '('){
while(stack[top] != ')'){
Posfix.append(stack[top]);
top--;
}
top--;// ( 不輸出
}else{
Posfix.append(Infix[i]) ;
}
}
 while(top > 0){
 Posfix.append(stack[top]);
     top--;
 }
return Posfix.reverse().toString();

}
static String ToInFix(char[] prefix){
String[] stack = new String[prefix.length]; //運算式堆疊
StringBuffer InFix = new StringBuffer(); //輸出:中序式
char[] Prefix = prefix;

int top = 0; 
for(int i = Prefix.length - 1; i >= 0; i--){  // stack 2 + op + stack 1
if(Prefix[i] == '+'|| Prefix[i] == '-'||Prefix[i] == '*' || Prefix[i] == '/'){
  String s = stack[top] ;
  stack[top] = null ;
  String s2 = stack[--top] ;
 if(Prefix[i] == '+'|| Prefix[i] == '-')
 stack[top] = "("+s+Prefix[i]+s2+")";
 else
  stack[top] = s+Prefix[i]+s2;  
}else{
top++;
stack[top] =String.valueOf(Prefix[i]) ;

}

}
for(String s : stack){
if(s != null)
InFix.append(s);
}
return InFix.toString();
}


}

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。