0
public class Convert{ 
/* the algorithm works as follows after inserting all elements of infix string 
into an empty Queue iterate over queue for infix.length() number of times and 
check if element at front of queue is an operator if yes enque the element to 
back of the queue else deque the operand and concatenate it with the empty 
prefix string here is an example then finally deque the queue elements with 
the prefix string*/                  

    public static String Pre(String in){
        int i = 0;
        Queue Q = new Queue(in.length());     //assuming a Queue of characters
        while(i<in.length()){
            Q.enque(in.charAt(i));       
        }
        i = in.length()-1;
        String pre = "";
        while(i>=0){                         //move operators to end of queue
            if(Q.peek()=='+'||'-'){           //if character is oper enque at end 
                Q.enque(Q.deque);}
            else{
                pre  = pre + Q.deque;
            }            // concatenate operands with prefix 
        }
        while(!Q.isEmpty) {                        //concatenate the operators 
            pre = Q.deque + pre;
        }
        return pre;                               // end of method
    }
}
4

2 に答える 2

0

あなたが指定した非常に限られた文法を考えると、両頭キューを使用してインフィックスをプレフィックスに変換できるようです。文法がもっと複​​雑だったら、このアプローチがうまくいくとは思えません。

于 2011-10-23T16:31:54.810 に答える