包含min函数的栈 牛客网 剑指Offer
- 题目描述
- 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
class Solution:
def __init__(self):
self.stack = []
self.minStack = []
def push(self, node):
self.stack.append(node)
if self.minStack == [] or node < self.min():
self.minStack.append(node)
else:
temp = self.min()
self.minStack.append(temp)
def pop(self):
if self.stack == [] or self.minStack == []:
return None
self.minStack.pop()
self.stack.pop()
def top(self):
return self.stack[-1]
def min(self):
return self.minStack[-1]