当前位置: 首页 > 知识库问答 >
问题:

如何使用堆栈在一次扫描中计算内插表达式?

姬振
2023-03-14

我想知道是否有一种方法可以使用两个堆栈在一次传递中求解中缀表达式?堆栈可以是一个用于运算符,另一个用于操作数。。。

使用分流码算法求解的标准方法是将中缀表达式转换为后缀(反向波兰),然后求解。我不想先将表达式转换为后缀。

如果表达式类似于2*3-(6 5)8,如何求解?

共有3个答案

公孙嘉禧
2023-03-14
  • 创建一个空操作符堆栈。
  • 创建一个空操作数堆栈。
  • 对于输入字符串中的每个令牌
    a.获取内缀字符串中的下一个令牌。
    b.如果下一个是操作数,则将其放在操作数堆栈上。
    c.如果下一个令牌是运算符
    • 评估操作员。

谷梁楚青
2023-03-14

链接中给出的方法确实不错。

让我引述资料来源:

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.

我希望这有帮助!

陶璞
2023-03-14

很晚了,但答案是这样的。

取两叠:

  1. 运算符栈{用于运算符和括号}。
  2. 操作数栈.

如果字符存在要读取:

  1. 如果字符是操作数推压操作数堆栈,如果字符是),推压运算符堆栈

Else(没有更多字符可读取):

  • 弹出运算符,直到运算符栈不为空。
  • 操作数堆栈上弹出顶部2操作数推送op1 op op2

操作数堆栈返回顶部值。

 类似资料:
  • 我得到了一段代码来破译、解释和提供任何改进建议。我被告知它可以工作,我们不能运行代码来测试它。我很理解它,但只需要有人来运行它,以确保我所理解的是正确的,请获得任何帮助来解释我不理解的地方。我已经做了大量的研究,仍然有一些问题。 代码正在实现用于读取只使用乘法和加法的后缀表达式。然后计算表达式,同时将结果保存到堆栈中。然后打印出结果。操作数被推到堆栈上,然后当它读取运算符时,它从堆栈中弹出前2个操

  • 问题内容: 我需要在python中使用sympy计算下面的表达式吗? 在中,这种情况下如何在python中使用sympy计算表达式?请帮我。 问题答案: 该文档位于:http : //docs.sympy.org/。您应该真正阅读它! 要“计算”您的表达式,请编写如下代码: 就是这样。如果通过“计算”表示其他含义,则还可以求解exp = 0: 对于其他所有内容,您应该真正阅读文档。也许从这里开始:

  • 问题内容: 嗨,我正在尝试使用另一个空堆栈反转堆栈(我自己编写了一个堆栈)。由于某种原因,它无法正常工作。谁能帮我这个 ? 问题答案: while(!stack1.isEmpty()){ Integer value = (Integer)stack1.pop(); System.out.println(value); reverse.push(value); }

  • 我正在为我的一堂计算机科学课开发一个计算后缀表达式结果的程序。该程序使用堆栈ADT来实现这一点。 我已经编写了程序,但相信可能会有错误,因为一些表达式的结果不正确。我不确定我的错误在哪里。 此外,当输入文件为空时,程序将生成一个值32767。那是从哪里来的? 表达式:34+3*值=21。 主程序:

  • 第一篇文章是关于Stack的,对于使用Python和DynamoDB编程来说,这是相当新的,但是我只是想在我的表上运行一个扫描,根据两个预定义的属性返回结果。 ---这是我的Python代码片段--- 我的发电机有4个磁场。 ID 日期 班次 安全 现在关于这个问题,在运行时,我得到了两个返回的表条目,而我应该只得到第一个条目...根据我的扫描标准,有“没有安全问题”的那个。 ---这是我的Dyn