find max value in a stack by push and pop without changing the stack by python: wirte code
时间: 2023-02-28 21:56:55 浏览: 85
基于C++和Python的多语言融合的ethos-n-driver-stack设计源码
下面是一种实现方法,可以在不改变栈顺序的情况下查找栈中的最大值:
```
class MaxStack:
def __init__(self):
self.stack = []
self.max_stack = []
def push(self, value):
self.stack.append(value)
if not self.max_stack or value >= self.max_stack[-1]:
self.max_stack.append(value)
def pop(self):
if self.stack:
value = self.stack.pop()
if value == self.max_stack[-1]:
self.max_stack.pop()
return value
return None
def max(self):
if self.max_stack:
return self.max_stack[-1]
return None
```
使用方法:
```
stack = MaxStack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.max()) # Output: 3
stack.pop()
print(stack.max()) # Output: 2
```
阅读全文