我试图了解我到底在问什么,也许你可以给我一些关于如何考虑解决这个问题的直觉。我需要用 Java 编写一个评估 Lisp 算术表达式的程序,但解决方案必须遵循特定的说明。
我需要评估这样的事情:
(+\t(- 6)\n\t(/\t(+ 3)\n\t\t(- \t(+ 1 1)\n\t\t\t3\n\t\t\t1)\n\t\t(*))\n\t(* 2 3 4))
我应该实现一个上下文堆栈,就是这样
Stack<Queue<Double>> contextStack
所以我猜这是一堆队列。我还有一个 ExpressionScanner 类,它扫描字符串并查找运算符和操作数:
public class ExpressionScanner
{
private String e;
private int position;
public ExpressionScanner(String e)
{
this.e = e;
this.position = 0;
}
public boolean hasNextOperator()
{
skipWhiteSpace();
return position < e.length() && isOperator(e.charAt(position));
}
public char nextOperator()
{
skipWhiteSpace();
return e.charAt(position++);
}
public boolean hasNextOperand()
{
skipWhiteSpace();
return position < e.length() && isDigit(e.charAt(position));
}
public int nextOperand()
{
skipWhiteSpace();
int operand = 0;
while (e.charAt(position) >= '0' && e.charAt(position) <='9')
operand = 10 * operand + e.charAt(position++) - '0';
return operand;
}
private void skipWhiteSpace()
{
char c;
while (position < e.length() && ((c = e.charAt(position)) == ' ' || c == '\t' || c == '\n'))
position++;
return;
}
private static boolean isOperator(char c)
{
return c == '(' || c == '+' || c == '-' || c == '*' || c == '/' || c == ')';
}
private static boolean isDigit(char c)
{
return c >= '0' && c <= '9';
}
} /*201340*/
这就是我的解决方案应该进入的地方,但我有点沮丧,因为我不知道如何使用那堆队列来实现解决方案。
import java.util.Queue;
import java.util.LinkedList;
import java.util.Stack;
public class IterativeEvaluator
{
private ExpressionScanner expression;
public IterativeEvaluator (String expression)
{
this.expression = new ExpressionScanner(expression);
}
public double evaluate(Queue<Double> operandQueue)
{
// write your code here to create an explicit context stack
char operator = ' ';
double operand = 0.0;
// write your code here to evaluate the LISP expression iteratively
// you will need to use an explicit stack to push and pop context objects
}
public static void main(String [] args)
{
String s =
"(+\t(- 6)\n\t(/\t(+ 3)\n\t\t(- \t(+ 1 1)\n\t\t\t3\n\t\t\t1)\n\t\t(*))\n\t(* 2 3 4))"; // = 16.5
IterativeEvaluator myEvaluator = new IterativeEvaluator(s);
System.out.println("Evaluating LISP Expression:\n" + s);
System.out.println("Value is: " + myEvaluator.evaluate(null));
}
} /* 201340 */
谢谢你的帮助。