diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index e38bc1a3..c8b0da08 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -224,6 +224,22 @@ var evalRPN = function(tokens) { }; ``` +python3 + +```python +def evalRPN(tokens) -> int: + stack = list() + for i in range(len(tokens)): + if tokens[i] not in ["+", "-", "*", "/"]: + stack.append(tokens[i]) + else: + tmp1 = stack.pop() + tmp2 = stack.pop() + res = eval(tmp2+tokens[i]+tmp1) + stack.append(str(int(res))) + return stack[-1] +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 10314a08..c2af71f7 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -282,6 +282,50 @@ class MyQueue { Python: +```python +# 使用两个栈实现先进先出的队列 +class MyQueue: + def __init__(self): + """ + Initialize your data structure here. + """ + self.stack1 = list() + self.stack2 = list() + + def push(self, x: int) -> None: + """ + Push element x to the back of queue. + """ + # self.stack1用于接受元素 + self.stack1.append(x) + + def pop(self) -> int: + """ + Removes the element from in front of queue and returns that element. + """ + # self.stack2用于弹出元素,如果self.stack2为[],则将self.stack1中元素全部弹出给self.stack2 + if self.stack2 == []: + while self.stack1: + tmp = self.stack1.pop() + self.stack2.append(tmp) + return self.stack2.pop() + + def peek(self) -> int: + """ + Get the front element. + """ + if self.stack2 == []: + while self.stack1: + tmp = self.stack1.pop() + self.stack2.append(tmp) + return self.stack2[-1] + + def empty(self) -> bool: + """ + Returns whether the queue is empty. + """ + return self.stack1 == [] and self.stack2 == [] +``` Go: