【问题标题】:How to evaluate Reverse polish notation using stacks如何使用堆栈评估反向波兰符号
【发布时间】:2017-03-12 18:06:32
【问题描述】:

这个后缀表达式可以求值吗?

6 2 3 + - 3 8 2 / + * 2 5 3 +

【问题讨论】:

  • 是的,你最终会在你的堆栈上得到 [7 2 8](从下到上)——表达式没有完全折叠,因为没有足够的运算符。您可以使用dc 进行检查:6 2 3 + - 3 8 2 / + * 2 5 3 + f 评估您的 RPN 表达式并转储堆栈 (f)。 (但这并不是真正的编程问题,除非你问的是代码......)
  • 我投票决定将此问题作为离题结束,因为它与编程无关 - 仅与 特定 RPN 表达式的评估有关。

标签: algorithm stack postfix-notation rpn


【解决方案1】:

是的,可以。

S = new empty stack
while not eof
    t = read token
    if t is a binary operator
        y = pop(S)
        x = pop(S)
        push(S, t(x, y))
    else
        push(S, t)
print the contents of the stack S

【讨论】:

    【解决方案2】:

    只需遍历整个数组,然后:

    • push 你遇到的每个number 堆栈
    • 如果遇到operation token - pop 堆栈中的两个数字并评估操作
    • push你的操作结果回栈

    就是这样。时间复杂度为linear, O(n),空间复杂度为linear, O(n),因为我们使用堆栈来存储数字。 整个代码使用栈(JavaScript):

    /*
      Function to perform operation with two numbers.
      @param {String} Operation type.
      @param {Number} Number 1.
      @param {Number} Number 2.
      @returns {Number} Result of performing the operation.
    */
    var performOperation = function performOperation(operation, num1, num2) {
        switch (operation) {
            case '+': return num1 + num2;
            case '-': return num1 - num2;
            case '*': return ~~(num1 * num2);
            case '/': return ~~(num1 / num2);
            default: console.error('Unknown operation: ', operation);
        }
    };
    /*
      Function to check if variable holds an operation type.
      @param {Any} Token.
      @returns {Boolean} If token is string with operation type.
    */
    var isOperation = function isNumber(token) {
        // map of supported operations
        var map = {
            '+': true,
            '-': true,
            '*': true,
            '/': true
        }
        return !!map[token];
    };
    
    var evaluatePolishNotation = function evaluatePolishNotation(tokens) {
      var stack = [];
      for (var i = 0; i < tokens.length; i++) {
        var token = tokens[i];
        if (isOperation(token)) {
          var number1 = stack.pop();
          var number2 = stack.pop();
          stack.push( performOperation(token, number2, number1) );
        } else {
          stack.push( parseInt(tokens[i], 10) );
        }
      }
      return stack.pop();
    }
    

    但是你可以通过使用常数空间 O(1) 来改进它!阅读更多关于算法的信息here

    【讨论】:

      猜你喜欢
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 2023-03-11
      • 1970-01-01
      • 2015-01-01
      • 2012-05-01
      相关资源
      最近更新 更多