import java.util.Stack;
public class LeetCode_middleTransformToReversePolish {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] input={"9","+","(","3","-","1",")","*","3","+","10","/","2"};
System.out.println(middleToBack(input));
}
public static String middleToBack(String[] input)
{
int length=input.length;
String result="";
boolean isHaveleftToken=false;
Stack stack=new Stack<>();
for(int i=0;i {
if(!isOperator(input[i]))
result=result+input[i];
else {
if(stack.isEmpty())
stack.push(input[i]);
else if(input[i].equals("*")||input[i].equals("/"))
{
String tempeek=stack.peek();
if(isHaveleftToken)
stack.push(input[i]);
else {
if(tempeek.equals("*")||tempeek.equals("/"))
result=result+stack.pop();
stack.push(input[i]);
}
}
else if(input[i].equals("("))
{
isHaveleftToken=true;
stack.push(input[i]);
}
else if(input[i].equals(")"))
{
String temp=stack.pop();
while(!temp.equals("("))
{
result=result+temp;
temp=stack.pop();
}
isHaveleftToken=false;
}
else {
if(isHaveleftToken)
stack.push(input[i]);
else {
while(!stack.isEmpty())
result=result+stack.pop();
stack.push(input[i]);
}
}
}
}
//加上栈中还没出栈的元素
while(!stack.isEmpty())
{
result=result+stack.pop();
}
return result;
}
public static boolean isOperator(String s)
{
if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")||s.equals("(")||s.equals(")"))
return true;
else
return false;
}
}
总体思路是这种:遇到数字的话直接输出,遇到右括号 输出左括号上面的所有元素 ,遇到左括号入栈。遇到乘除符号。进行推断假设栈中有左括号或栈顶元素是加减就入栈其余出栈。遇到加减符号,假设栈中有左括号则入栈,否则将栈中元素所有出栈。做完这些处理后,在将栈中还没出栈的增加到输出结果中。亲測实用