实现栈的数据结构,并在其中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。
# -*- coding:utf-8 -*-
class StackwithMin:
def __init__(self, stack=[]):
self.stack = stack
self.stack_min = []
self.num_min = None
def push(self, node):
# write code here
self.stack.append(node)
if self.num_min is None or node < self.num_min:
self.num_min = node
self.stack_min.append(self.num_min)
def pop(self):
# write code here
result = self.stack.pop()
self.stack_min.pop()
return result
def top(self):
# write code here
return self.stack[-1]
def min(self):
# write code here
return self.stack_min[-1]