我正在处理基本上是调车场算法的东西,但是将中缀表达式转换为前缀表达式而不是逆波兰表达式。 我试图保留括号,但是遇到了极大的困难。目前我的代码是:
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);
这段代码正确地输出了左括号,但只输出了一种右括号。请问有人知道我应该在哪里添加它们吗?我发誓我缺少那个最后的逻辑步骤来弄清楚它应该放在哪里...