【发布时间】:2021-10-30 11:18:43
【问题描述】:
我目前正在尝试创建一个将前缀表达式转换为后缀表达式的程序,但在让我的堆栈按预期工作时遇到了很多麻烦。
我的目标是创建一个反转堆栈来存储初始前缀表达式,然后一个接一个地弹出标记。
StringTokenizer defaultTokenizer = new StringTokenizer(expression, " ", false);
//First while loop to push tokens on reversal stack
while (defaultTokenizer.hasMoreTokens()) {
String c = defaultTokenizer.nextToken();
reversalStack.push(c + " ");
}
如果标记是操作数:
如果它们是操作数,则将它们添加到操作数堆栈中
否则,如果下一个标记是运算符:
弹出两个操作数,用运算符将它们添加到一个字符串中,然后将它们添加到操作数堆栈中
//Second while loop that pops the reversal stack one at a time
while (reversalStack.isEmpty() == false) {
String c = reversalStack.pop();
//if the token is an operand, add it to the operand stack
if(!isOperator(c) == true){
operandStack.push(c);
//if the token is an operator, pop two operands, combine them with the operator
//into one string and push them into the operand stack as one string
}else{
String op1 = operandStack.pop();
String op2 = operandStack.pop();
String temp = op1 + op2 + c;
operandStack.push(temp);
}
}
//Pop the postfix expression
String result = operandStack.pop();
return result;
}
我正在测试的当前前缀表达式是“* 2 + 2 - + 12 9 2”,但我只得到作为输出的乘法符号。如果我的问题出在我的代码中的其他地方,我在下面添加了整个类。
import java.util.Stack;
import java.util.StringTokenizer;
Public class Main {
static Stack<String> reversalStack = new Stack<String>();
static Stack<String> operandStack = new Stack<String>();
public static void main(String[] args) {
String test = "* 2 + 2 - + 12 9 2";
System.out.println(test);
System.out.println(new Main().convert(test));
}
boolean isOperator(String x){
switch (x){
case "-":
case "+":
case "/":
case "*":
case "^":
return true;
}
return false;
}
public String convert(String expression) {
StringTokenizer defaultTokenizer = new StringTokenizer(expression, " ", false);
//First while loop to push tokens on reversal stack
while (defaultTokenizer.hasMoreTokens()) {
String c = defaultTokenizer.nextToken();
reversalStack.push(c + " ");
}
//Second while loop that pops the reversal stack one at a time
while (reversalStack.isEmpty() == false) {
String c = reversalStack.pop();
//if the token is an operand, add it to the operand stack
if(!isOperator(c) == true){
operandStack.push(c);
//if the token is an operator, pop two operands, combine them with the operator
//into one string and push them into the operand stack as one string
}else{
String op1 = operandStack.pop();
String op2 = operandStack.pop();
String temp = op1 + op2 + c;
operandStack.push(temp);
}
}
//Pop the postfix expression
String result = operandStack.pop();
return result;
}
}
对于格式错误,我很抱歉,我在复制粘贴我的代码时遇到了问题。任何帮助将不胜感激!
【问题讨论】:
-
你想多了。弹出您的前缀堆栈并将其推送到后缀堆栈中。在前缀堆栈非空时冲洗并重复。 “使用运算符将它们添加到一个字符串中”是完全错误的,因此有两个堆栈也是如此。或者直接拨打
reverse(),无论它在哪里 (Collections?)。