3 回答
TA贡献1852条经验 获得超1个赞
很晚了,但这是答案。
取两叠:
operator stack
{用于运算符和括号}。operand stack
。
算法
如果存在要读取的字符:
如果
operand
按下字符operand stack
,如果(
按下字符operator stack
。否则,如果字符是
operator
而的顶部
operator stack
优先级比此字符小。operator
从弹出operator stack
。从中弹出两个
operands
(op1
和op2
)operand stack
。存储
op1 op op2
在operand stack
回2.1。否则
)
,请执行2.2-2.4的操作,直到遇到为止(
。
其他(不再需要阅读其他字符):
弹出运算符,直到
operator stack
不为空。弹出顶部2,
operands
然后push op1 op op2
在上operand stack
。
返回的最高值operand stack
。
TA贡献1875条经验 获得超5个赞
链接中给出的方法确实很好。
让我引用来源:
We will use two stacks:
Operand stack: to keep values (numbers) and
Operator stack: to keep operators (+, -, *, . and ^).
In the following, “process” means, (i) pop operand stack once (value1) (ii) pop operator stack once (operator) (iii) pop operand stack again (value2) (iv) compute value1 operator value2 (v) push the value obtained in operand stack.
Algorithm:
Until the end of the expression is reached, get one character and perform only one of the steps (a) through (f):
(a) If the character is an operand, push it onto the operand stack.
(b) If the character is an operator, and the operator stack is empty then push it onto the operator stack.
(c) If the character is an operator and the operator stack is not empty, and the character's precedence is greater than the precedence of the stack top of operator stack, then push the character onto the operator stack.
(d) If the character is "(", then push it onto operator stack.
(e) If the character is ")", then "process" as explained above until the corresponding "(" is encountered in operator stack. At this stage POP the operator stack and ignore "(."
(f) If cases (a), (b), (c), (d) and (e) do not apply, then process as explained above.
When there are no more input characters, keep processing until the operator stack becomes empty. The values left in the operand stack is the final result of the expression.
我希望这有帮助!
添加回答
举报