简介
后缀表达式便于使用栈进行计算。当一个表达式以后缀记号给出时,没有必要知道任何优先的规则,这是一个明显的优点。其花费的计算时间是O(N)。本文将介绍如何将中缀表达式转换为后缀表达式(后缀表达式的计算将不再阐述)。
数据结构
原始的字符串被储存在一个数组中。栈和队列被用来处理这些数据。
算法实现
当读到第一个操作数的时候,立即把它放到queue中。而遇到操作符时,则通过stack进行处理。如果空栈,将操作符推入栈中,左圆括号也推入栈中。如果见到其他符号,我们从栈中弹出栈元素直到发现优先级更低的元素为止,除了“(”——如果没有遇到“)”则永远不将(弹出。在这里,我将优先级以int priority表达:+-的优先级为1,*/的优先级为2而(的优先级最高为3,那么如果栈中有+,还可以塞进一个*或/或(。而遇见+-则先将栈中的运算符弹出并加入queue中再将操作符塞入栈。在处理(的时候,如果将(塞入栈,则priority为0,以便塞入别的运算符而不会将(弹出。在(弹出后,判断栈顶的运算符并重新判断优先级,由于我水平欠佳,该过程变得相当麻烦。在最后打印的时候,()不打印出来。
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Main {
public static String reverseP(String[] str){
Stack st=new Stack();
Queue qu=new LinkedList();
int priority=0;
for(int i=0;i<str.length;i++){
if(str[i].matches("\\d")){
qu.offer(str[i]);
System.out.println(str[i]+" offered");
}
else if(str[i].matches("[+-]")){
if(priority<1){
st.push(str[i]);
System.out.println(st.peek()+" pushed into stack");
priority=1;}
else
{
while(!st.empty()&&!(st.peek().equals("(")))
{
System.out.println(st.peek()+" offered");
qu.offer(st.pop());
//System.out.println(st.peek()+" on top");
}
st.push(str[i]);
System.out.println(st.peek()+" pushed into stack");
priority=1;
}
}
else if(str[i].matches("[*/]")){
if(priority<2){
st.push(str[i]);
System.out.println(st.peek()+" pushed into stack");
priority=2;}
else
{
while(!st.empty()&&!st.peek().equals("("))
{
System.out.println(st.peek()+" offered");
qu.offer(st.pop());
}
st.push(str[i]);
System.out.println(st.peek()+" pushed into stack");
priority=2;
}
}
else if(str[i].matches("[(]")){
st.push(str[i]);
System.out.println(st.peek()+" pushed into stack");
priority=0;
}
else if(str[i].matches(("[)]"))){
String temp;
do
{
temp=(String) st.peek();
System.out.println(temp+" offered");
qu.offer(st.pop());
}
while(!st.empty()&&temp.equals("("));
qu.offer(st.pop());
qu.offer(str[i]);
System.out.println(")offered");
if((st.peek().equals("+"))||st.peek().equals("-"))
{
priority=1;
}
else if((st.peek().equals("*"))||st.peek().equals("/"))
{
priority=2;
}
else
priority=0;
}
}
System.out.println("the remanent in the stack");
while(!st.empty())
{
String rem=(String) st.peek();
if(!rem.matches("[()]"))
System.out.println(st.peek());
qu.offer(st.pop());
}
String output ="";
int u=qu.size();
for(int i=0;i<u;i++){
String t=(String) qu.poll();
if(!t.matches("[()]"))
output+=t;
}
//String[] output=new String[qu.size()];
return output;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] b=new String[]{"1","+","2","*","3","+","(","4","*","5","+","6",")","*","7","+","9","*","9"};
String a=reverseP(b);
System.out.println(a);
}
}