定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.minValue = [] #用来存储当前最小值
def push(self, node):
self.stack.append(node)
if self.minValue:
if self.minValue[-1] > node:
self.minValue.append(node)
else:
self.minValue.append(self.minValue[-1])
else:
self.minValue.append(node)
# write code here
def pop(self):
if self.stack == []:
return None
self.minValue.pop()
return self.stack.pop()
# write code here
def top(self):
if self.stack == []:
return None
return self.stack[-1]
# write code here
def min(self):
if self.minValue == []:
return None
return self.minValue[-1]
# write code here