面试题21:包含min函数的栈
2018-07-08 本文已影响0人
fighting_css
【题目】定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数。
【思路】
image.png
引入辅助栈min_stack,保持栈顶为该栈最小值
【代码】
class Solution:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, node):
# write code here
self.stack.append(node)
if len(self.min_stack)==0:
self.min_stack.append(node)
else:
if node<self.min_stack[-1]:
self.min_stack.append(node)
else:
self.min_stack.append(self.min_stack[-1])
def pop(self):
# write code here
if len(self.stack) == 0:
return
else:
self.min_stack.pop()
a = self.stack.pop()
return a
def top(self):
# write code here
if len(self.stack) == 0:
return
return self.stack[-1]
def min(self):
# write code here
if len(self.min_stack) == 0:
return
return self.min_stack[-1]