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

问题

  • 计算给定的逆波兰表达式的值,有效操作只有 + / ,每个操作数都是整数;
  • 例如:
    • ”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;
}

猜你喜欢

转载自blog.csdn.net/zkp_java/article/details/80740407