2012年5月19日 星期六

Java 中序式轉後序式


import java.util.*;

public class Postfix{
    public static int priority(String str){
        switch( str ){
            case "+": case "-": 
                return 1;
            case "*": case"/": case "%": 
                return 2;
            default: 
                return 0;
        }
    }

    public static String toPostfix(String str){
        StringBuffer sb = new StringBuffer();
        LinkedList<String> stack = new LinkedList<String>();
        for(String sub : str.split(" ") ){
            if("(".indexOf(sub) != -1){
                stack.add(sub);
            }else if("+-*/%".indexOf(sub) != -1){
                while(!stack.isEmpty() && priority(stack.getLast()) >= priority(sub)){
                    sb.append(stack.removeLast() + " ");
                }
                stack.add(sub);
            }else if(")".indexOf(sub) != -1){
                while( "(".indexOf(stack.getLast()) == -1 ){
                    sb.append(stack.removeLast() + " ");
                }
                stack.removeLast();
            }else{
                sb.append(sub + " ");
            }
        }
  
        while(!stack.isEmpty()){ sb.append(stack.removeLast()); }
        return sb.toString();
    }
 
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str;
  
        while( sc.hasNext() ){
            str = sc.nextLine();
            System.out.println( toPostfix(str) );
        }
    }
}

參考:良葛格學習筆記

沒有留言:

張貼留言