我正在研究本质上是调车场算法,但是将中缀移动到前缀而不是 RPN 我试图保留括号,而且我正在经历一段魔鬼时期。目前我的代码是
String s = inFixList.get(i);
Stack<Character> opStack = new Stack<Character>();
Stack<Character> solutionStack = new Stack<Character>();
String solution = "";
for(char c : s.toCharArray())
{
if(Character.isLetter(c)||Character.isDigit(c))
{
solutionStack.push(c);
}
else if(c == '(')
{
opStack.push(c);
solutionStack.push(')');
}
else if(c == ')')
{
while(opStack.peek() != '(')
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
}
opStack.pop();
}
else if (!Character.isSpaceChar(c))
{
if(opStack.isEmpty())
{
opStack.push(c);
}
else if(opStack.peek()!='(' &&(OPERATORS.indexOf(c) < OPERATORS.indexOf(opStack.peek())))
{
opStack.push(c);
}
else if(!opStack.isEmpty()&&(opStack.peek()!='('))
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
opStack.push(c);
}
else
{
opStack.push(c);
}
}
}
while(opStack.size() != 0)
{
solutionStack.push(opStack.pop());
solutionStack.push('(');
}
while(!solutionStack.isEmpty())
{
solution+=solutionStack.pop();
}
System.out.println("Final Answer!"+solution);
这会正确输出左括号,但只有一种右括号。有人知道我应该在哪里添加它们吗?我发誓我错过了最后一个合乎逻辑的步骤来获得它的去向......