题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def __init__(self): 4 self.stack1=[] 5 self.stack2=[] 6 def push(self, node): 7 # write code here 8 self.stack1.append(node) 9 if len(self.stack2)==0 or self.stack2[-1]>node: 10 self.stack2.append(node) 11 else: 12 self.stack2.append(self.stack2[-1]) 13 def pop(self): 14 if len(self.stack1)>0: 15 self.stack2.pop() 16 return self.stack1.pop() 17 # write code here 18 def top(self): 19 # write code here 20 if len(self.stack1)>0: 21 return self.stack1[-1] 22 def min(self): 23 # write code here 24 if len(self.stack2)>0: 25 return self.stack2[-1]