将前缀转换为后缀



我目前正在尝试创建一个将前缀表达式转换为后缀表达式的程序,但我在使堆栈按预期工作方面遇到了很多麻烦。

我的目标是创建一个反转堆栈,它将存储初始前缀表达式,然后逐个弹出令牌。

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 + " ");
}

如果令牌是操作数:

如果它们是操作数,则将它们添加到操作数堆栈

else,如果下一个令牌是操作符:

取出两个操作数,用操作符将它们加到一个字符串中,然后将它们加到操作数堆栈

//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;
}

}

对不起的格式错误,我有问题复制粘贴我的代码。任何帮助将非常感激!

您只获得一个操作数项,因为您只从操作数堆栈中取出其中一个作为返回值:

String result = operandStack.pop();
return result;

Stack.pop () javadoc:

public E pop():移除顶部的对象返回该对象作为该函数的值。

最新更新