双栈实现算数表达式

双栈算术表达式求值算法

源代码是java实现的,先把他改成cpp实现。

原理大家应该都懂,就是两个栈,一个保存读取式子的符号,遇到“(”不读,遇到“)”进行操作,其他符号保存。另一个栈保存每次读到的数字。

因为每次读到)时候,都要进行一次操作,而操作对象就是最小的那对括号里面的数字,也就是第二个栈顶保存的两个元素,所以可操作。

#include <iostream>
#include <stack> 
#include <vector>
#include <deque>
#include <string>
#include <math.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;

int main()
{
    stack<double> a;
    stack<string> b;
    string str;
    while(cin>>str)//每次读入的时候遇到空格才会停下,所以每输入一个元素要输入一个空格,不知怎么解决。
    {
        if(str=="(");
        else if(str=="+") b.push(str);
        else if(str=="-") b.push(str);
        else if(str=="*") b.push(str);
        else if(str=="sqrt") b.push(str);
        else if(str
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以用来实现算数表达式的计算。 具体实现步骤如下: 1. 创建一个操作数和一个操作符。 2. 从左到右遍历表达式,对于每个字符: - 如果它是一个数字,则将其压入操作数。 - 如果它是一个操作符,则将其压入操作符。 - 如果它是一个右括号,则弹出操作符中的操作符和操作数中的操作数,直到遇到左括号为止。然后将计算结果压入操作数。 3. 最后,操作符中可能还有操作符,需要按照优先级顺序弹出操作符并计算,直到操作符为空。最后的操作数中的元素即为表达式的计算结果。 下面是一个示例代码,实现了一个简单的算数表达式计算器: ```python class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def is_empty(self): return len(self.items) == 0 def calculate(expression): precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '(': 0, ')': 0} operand_stack = Stack() operator_stack = Stack() for token in expression: if token.isdigit(): operand_stack.push(int(token)) elif token in '+-*/': while not operator_stack.is_empty() and precedence[token] <= precedence[operator_stack.peek()]: operator = operator_stack.pop() operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = eval(f'{operand1} {operator} {operand2}') operand_stack.push(result) operator_stack.push(token) elif token == '(': operator_stack.push(token) elif token == ')': while operator_stack.peek() != '(': operator = operator_stack.pop() operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = eval(f'{operand1} {operator} {operand2}') operand_stack.push(result) operator_stack.pop() while not operator_stack.is_empty(): operator = operator_stack.pop() operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = eval(f'{operand1} {operator} {operand2}') operand_stack.push(result) return operand_stack.pop() expression = '2 * (3 + 4) - 5 / 2' result = calculate(expression) print(f'{expression} = {result}') ``` 输出结果为: ``` 2 * (3 + 4) - 5 / 2 = 13.5 ``` 注意,这个实现只支持整数和四则运算,没有处理错误输入和除数为0的情况。在实际应用中,需要加入更多的判断和处理逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值