[算法] 逆波兰表达式(栈实现)

10 篇文章 0 订阅

问题

  • 计算给定的逆波兰表达式的值,有效操作只有 +/ + − ∗ / ,每个操作数都是整数;
  • 例如:
    • ”2”, “1”, “+”, “3”, “*” : 9,(2+1)*3
    • “4”, “13”, “5”, “/”, “+” : 6,4+(13/5)

分析

  • 对于逆波兰表达式abc-d*;
  • 若当前字符是操作数,则压栈;
  • 若当前字符是操作符,则弹出栈中的两个操作数,计算后仍然压入栈中:
    • 若某次操作,栈中无法弹出两个操作数,则表达式有误

代码实现

代码实现如ReversePolishNotation.hpp所示:

#ifndef ReversePolishNotation_hpp
#define ReversePolishNotation_hpp

#include <stdio.h>

// 判断给定字符串是否为操作符
bool isOperator(const char* token) {
    return ((token[0] == '+') || (token[0] == '-') || (token[0] == '*') || (token[0] == '/'));
}

// 计算逆波兰表达式的值
int computeReversePolishNotation(const char* str[], int size) {
    std::stack<int> s;
    int a, b;
    const char* token;
    for (int i = 0; i < size; i++) {
        token = str[i];
        if (!isOperator(token)) {
            s.push(atoi(token));
        } else {
            b = s.top();
            s.pop();
            a = s.top();
            s.pop();
            if (token[0] == '+') {
                s.push(a+b);
            } else if(token[0] == '-') {
                s.push(a-b);
            } else if(token[0] == '*') {
                s.push(a*b);
            } else if(token[0] == '/') {
                s.push(a/b);
            }
        }
    }
    return s.top();
}
#endif /* ReversePolishNotation_hpp */

测试代码main.cpp:

#include "ReversePolishNotation.hpp"

int main(int argc, const char * argv[]) {
    const char* str[] = {"2", "1", "+", "3", "*"};
    int value = computeReversePolishNotation(str, 5);
    printf("%d\n", value);
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值