3
A
回答
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。
相關問題
- 1. 逆波蘭表示法Java
- 2. 逆波蘭表示法和堆棧。使用valueOf方法時出錯。爪哇
- 3. 逆波蘭表示法的CFG
- 4. 轉換逆向波蘭表示法
- 5. C++反向波蘭語表示法堆棧
- 6. 逆向算法逆波蘭式
- 7. java中使用堆棧的Postfix評估
- 8. 使用堆棧後綴評估
- 9. Postfix評估代碼使用堆棧
- 10. 使用堆棧評估Posfix(LinkedList)
- 11. 使用堆棧進行Postfix評估。
- 12. 評估與堆棧的表達式
- 13. 堆棧和評估後綴
- 14. 逆向波蘭語表示法(RPN)或後綴表示法的重構反饋
- 15. 逆向波蘭語表示法疑難解答C
- 16. 如何將這些表達式轉換爲逆波蘭表示法?
- 17. 如何避免使用此評估(BFS)的堆棧溢出
- 18. 使用Java堆棧評估有效的Lisp表達式
- 19. 通過使用反向波蘭記法和使用堆棧計算器
- 20. 使用多堆棧評估前綴表達式
- 21. 使用堆棧評估前綴表達式
- 22. 使用堆棧和C++字符數組評估Postfix表達式
- 23. 在C++中使用堆棧來評估後綴表達式
- 24. 如何在條件逆波蘭公式中使用AND/OR?
- 25. 需要幫助瞭解如何在高級逆向波蘭表示法程序中使用堆棧和二叉搜索樹相關
- 26. Java的RPN(逆波蘭式)綴與postfix
- 27. 逆波蘭給出錯誤的答案
- 28. NET CIL操作評估堆棧
- 29. 可逆字堆棧
- 30. Z3py波蘭表示法輸出
是的,你最終會在堆棧中找到[7 2 8](從下到上) - 由於沒有足夠的操作符,表達式不會完全崩潰。您可以使用'dc'來檢查:'6 2 3 + - 3 8 2/+ * 2 5 3 + f'評估您的RPN表達式並轉儲堆棧('f')。 (但是,除非你詢問代碼,否則這不是一個真正的_programming_問題) – nneonneo
我正在投票結束這個題目,因爲它不是關於編程 - 只關於_particular_ RPN表達式的評估。 – nneonneo