> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/bu-chong-2140-dao/150.-evaluate-reverse-polish-notation.md).

# 150. Evaluate Reverse Polish Notation

{% hint style="info" %}
Not hard if know the principle behind and coding as the process of human solving

Key idea: when see notation, compute the two numbers before it.&#x20;

`stack` is perfect to this problem
{% endhint %}

### Solution:

1. traversal all elements of the list
2. if it's a number, push to stack
3. if it's a notation, pop two numbers and compute, then push back to stack

```python
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:      
        i = 0
        stack = []
        while i < len(tokens):
            st = tokens[i]
            if st != '+' and st != '-' and st != '*' and st != '/':
                stack.append(st)
            else:
                num2 = int(stack.pop())
                num1 = int(stack.pop())
                if st == '+':
                    res = num1 + num2
                elif st == '-':
                    res = num1 - num2
                elif st == '*':
                    res = num1 * num2
                else:
                    if num1*num2 < 0:
                        res = num1*(-1)//num2 * (-1)
                    else:
                        res = num1//num2
                stack.append(res)
            i += 1
        
        return stack.pop()
```

{% hint style="danger" %}
如果用python则不能用recursive来做，因为python不能传递reference，意味着函数的参数无法成为全局变量，而导致一直在变
{% endhint %}

Time = $$o(n)$$ , space = $$O(n)$$&#x20;


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://r24zeng.gitbook.io/leetcode-notebook/bu-chong-2140-dao/150.-evaluate-reverse-polish-notation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
