2016-10-30 70 views
3

可以評估此​​後綴表達式嗎?如何評估使用堆棧的逆波蘭表示法

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

是的,你最終會在堆棧中找到[7 2 8](從下到上) - 由於沒有足夠的操作符,表達式不會完全崩潰。您可以使用'dc'來檢查:'6 2 3 + - 3 8 2/+ * 2 5 3 + f'評估您的RPN表達式並轉儲堆棧('f')。 (但是,除非你詢問代碼,否則這不是一個真正的_programming_問題) – nneonneo

+0

我正在投票結束這個題目,因爲它不是關於編程 - 只關於_particular_ RPN表達式的評估。 – nneonneo

回答

4

是的,它可以。

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 
1

簡單地重複通整個陣列和:

  • 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