可以仅使用队列将中缀表示法中的字符串转换为前缀表示法吗? (考虑唯一的操作是 + 和 - 的情况)
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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“帖子”生产系统仅使用队列。它具有与图灵机相当的能力。
A "Post" Production System uses only queues. It has equivalent power to a Turing Machine.
鉴于您指定的语法非常有限,对我来说,您似乎可以使用双端队列将中缀转换为前缀。如果语法更复杂,我怀疑这种方法是否有效。
Given the very limited grammar you specified, to me it appears that you could convert infix to prefix using a double-ended queue. Were the grammar more complex I doubt that this approach would work.