给定表达式:
1/2/3/4*5
它到达表达式的末尾并尝试先将 4 和 5 相乘,这是错误的,因为它开始从堆栈中弹出。我不一定要做RPN,而只是在现场进行评估。我怎样才能防止这种情况?
// Expression was completely read - so we should try and make sense of
// this now
while (operatorStack.size() != 0) {
ApplyOperation(operatorStack, operandStack);
}
在这一点上,我开始弹出操作符和操作。由于乘法和除法具有相同的存在,它们从乘法开始。
一个痕迹:
1/2/3/4*5
Applying * to 5 and 4
Result: 20
Applying / to 20 and 3
Result: 3/20
Applying / to 3/20 and 2
Result: 40/3
Applying / to 40/3 and 1
Result: 3/40