Python 中 list 自带的 append 和 pop 方法默认行为就是栈的 push 和 pop,top 方法返回 Buf[-1] 即可;
Python
classMinStack:def__init__(self):""" initialize your data structure here. """ self.Buf = [] self.Min = []defpush(self,x:int) ->None: self.Buf.append(x)ifnot self.Min or x <= self.Min[-1]:# 注意这里是小于等于 self.Min.append(x)defpop(self) ->None: x = self.Buf.pop()if x == self.Min[-1]: self.Min.pop()deftop(self) ->int:return self.Buf[-1]defmin(self) ->int:return self.Min[-1]# Your MinStack object will be instantiated and called as such:# obj = MinStack()# obj.push(x)# obj.pop()# param_3 = obj.top()# param_4 = obj.min()