题目出自《程序员代码面试指南》
1.1 最小栈
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
-
push(x) -- 将元素 x 推入栈中。
-
pop() -- 删除栈顶的元素。
-
top() -- 获取栈顶元素。
-
getMin() -- 检索栈中的最小元素。
python内的list来实现栈
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
#定义一个列表
self.stack = []
#push(x) -- 将元素 x 推入栈中。
def push(self, x: int) -> None:
self.stack.append(x)
#pop() -- 删除栈顶的元素。
def pop(self) -> None:
length = len(self.stack)
self.stack = self.stack[:length-1]
#top() -- 获取栈顶元素。
def top(self) -> int:
return self.stack[-1]
#getMin() -- 检索栈中的最小元素。
def getMin(self) -> int:
return min(self.stack)
# Your MinStack object