我需要使用链接列表堆栈评估postfix表达式。我想我需要一些关于算法的帮助。我写13+
作为输入,但我得到100
作为输出。使用堆栈评估Posfix(LinkedList)
PostfixCalculator类别:
public class PostfixCalculator{
String expression;
MyStack stack = new MyStack<Double>();
public PostfixCalculator(String postFixExpression)
{
expression = postFixExpression;
}
public String calculate()
{
String output = "";
char character = ' ';
double digit = 0;
for(int x = 0; x < expression.length(); x++)
{
if(Character.isDigit(expression.charAt(x))) {
digit = expression.charAt(x);
}
character = expression.charAt(x);
if(expression.charAt(x) == digit)
{
stack.push(digit);
}
else if(character == '*')
{
double tmp = (double) stack.pop() * (double) stack.pop();
stack.push(tmp);
}
else if(character == '/')
{
double tmp = (double) stack.pop()/(double) stack.pop();
stack.push(tmp);
}
else if(character == '+')
{
double tmp = (double) stack.pop() + (double) stack.pop();
stack.push(tmp);
}
else if(character == '-')
{
double tmp = (double) stack.pop() - (double) stack.pop();
stack.push(tmp);
}
}
while(!stack.isEmpty())
{
output = output + (double) stack.pop();
}
return output;
}
}
PostfixCalculatorTest类别:
import java.util.Scanner;
public class PostfixCalculatorTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type the postfix expression that you want to evaluate");
String expression = input.next();
PostfixCalculator calculator = new PostfixCalculator(expression);
System.out.println(calculator.calculate());
}
}
嗯,首先,你要将字符放入声明为“Double”的MyStack中。这将强制从'char'转换为'double'并打印你的角色的数字值 – nem035 2014-11-05 16:37:48