你好,我正在练习Java上的一些堆栈,我正在尝试做一个关于堆栈的问题。我正在尝试编写一个方法,它接受后缀符号并将其转换为中缀。这就是我到目前为止所知道的:
`
public void convertion() {
Stack<Integer> stack; // For evaluating the expression.
stack = new Stack<Integer>(); // Make a new, empty stack.
Scanner scan = new Scanner(postfix);
int t1, t2 = 0; //Operands
boolean check = false;
while (scan.hasNext() && !check) {
if (scan.hasNextInt()) {
int operand = scan.nextInt();
stack.push(operand);
} else {
char operator = scan.next().charAt(0);
try {
while(stack.)
} catch (EmptyStackException e) {
answer = "Malformed postfix expression";
check = true;
}
}
}
scan.close();
try {
answer = "" + stack.pop();
} catch (EmptyStackException e) {
answer = "Malformed postfix expression";
}
}
`我遇到麻烦的部分是关于我应该把什么放在try部分。基本上我把我找到的所有数字都压入栈中,但是一旦我找到一个运算符,我如何合并这两个操作数和运算符。
谢谢。
发布于 2013-04-06 10:43:50
您想要弹出最上面的两个堆栈元素,对它们执行适当的操作,然后推送结果:
try {
int o1 = stack.pop().intValue();
int o2 = stack.pop().intValue();
switch (operator) {
case '+': stack.push(new Integer(o1 + o2));
break;
case '-': stack.push(new Integer(o1 - o2));
break;
...
}
}
catch (EmptyStackException e) {
...https://stackoverflow.com/questions/15845824
复制相似问题