题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
实现代码:
class Solution:
def __init__(self):
self.min_stack=[]
self.stack=[]
def push(self, node):
# write code here
self.stack.append(node)
if self.min_stack==[] or node<=self.min_stack[-1]:
self.min_stack.append(node)
def pop(self):
# write code here
if len(self.stack)==0:
return None
out = self.stack.pop()
if out==self.min_stack[-1]:
self.min_stack.pop()
return out
def top(self):
# write code here
if len(self.stack)==0:
return None
return self.stack[-1]
def min(self):
# write code here
if len(self.stack)==0:
return None
return self.min_stack[-1]