如何使用堆栈在一次扫描中评估中缀表达式? [英] How to evaluate an infix expression in just one scan using stacks?
本文介绍了如何使用堆栈在一次扫描中评估中缀表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有办法使用 2 个堆栈一次性解决中缀表达式?堆栈可以一个用于运算符,另一个用于操作数...
I want to know if there is a way to solve infix expressions in a single pass using 2 stacks? The stacks can be one for operator and the other for operands...
分流码算法求解的标准方法是将中缀表达式转换为后缀(反向抛光)然后求解.我不想先将表达式转换为后缀.
The standard way to solve by shunt-yard algorithm is to convert the infix expression to postfix(reverse polish) and then solve. I don't want to convert the expression first to postfix.
如果表达式像2*3-(6+5)+8
,如何解决?
If the expression is like 2*3-(6+5)+8
, how to solve?
推荐答案
很晚了,但答案在这里.
Quite late, but here is the answer.
取两堆:
operator stack
{ 用于操作符和括号}.操作数栈
.
operator stack
{ for operators and parentheses }.operand stack
.
算法
如果存在要读取的字符:
Algorithm
If character exists to be read:
- 如果字符是
operand
,压入operand stack
,如果字符是(
,压入operand stack
>. - 否则如果字符是
operator
- If character is
operand
push on theoperand stack
, if character is(
, push on theoperator stack
. - Else if character is
operator
- 虽然
operator stack
顶部的优先级不低于此字符. - 从
operator stack
弹出operator
. - 从
operand stack
中弹出两个operands
(op1
和op2
). - 将
op1 op op2
存储在operand stack
回到 2.1.
- While the top of the
operator stack
is not of smaller precedence than this character. - Pop
operator
fromoperator stack
. - Pop two
operands
(op1
andop2
) fromoperand stack
. - Store
op1 op op2
on theoperand stack
back to 2.1.
)
,则与2.2 - 2.4 相同,直到遇到(
.
)
, do the same as 2.2 - 2.4 till you encounter (
.否则(没有更多字符可供阅读):
Else (no more character left to read):
- 弹出运算符直到
operator stack
不为空. - 在
operand stack
上弹出 top 2operands
和push op1 op2
.
- Pop operators untill
operator stack
is not empty. - Pop top 2
operands
andpush op1 op op2
on theoperand stack
.
从操作数栈
返回顶部值.
这篇关于如何使用堆栈在一次扫描中评估中缀表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文