程序员代码面试指南 python实现(第一章 栈和队列:实现一个有getMin功能的栈)
程序员代码面试指南 python实现(第一章 栈和队列)
设计一个有getMin功能的栈
题目描述
源码
不同的压栈对应不同的弹栈,就此分为两个方案,直接看代码
方案一:
''
定义一个标准的栈
'''
class stack(object):
def __init__(self):
self.item = []
def isEmpty(self):
return self.item == []
def push(self,numElem):
self.item.append(numElem)
def pop(self):
if self.isEmpty():
raise Exception("Your stack is empty")
else:
return self.item.pop()
def peek(self):
return self.item[len(self.item)-1]
def size(self):
return len(self.item)
'''
定义一个有getMin功能的stack
'''
class MyStack1(object):
def __init__(self):
self.stackData = stack()
self.stackMin = stack()
def getMin(self):
if self.stackMin.isEmpty():
raise Exception("Your stack is empty!")
else:
return self.stackMin.peek()
def push(self,numElem):
self.stackData.push(numElem)
if self.stackMin.isEmpty():
self.stackMin.push(numElem)
elif numElem <= self.stackMin.peek():
self.stackMin.push(numElem)
def pop(self):
value = self.stackData.pop()
if value == self.getMin():
self.stackMin.pop()
return value
def peek(self):
return self.stackData.peek()
def size(self):
return self.stackData.size()
方案2:
class MyStack2(object):
def __init__(self):
self.stackData = stack()
self.stackMin = stack()
def getMin(self):
return self.stackMin.peek()
def push(self,numElem):
self.stackData.push(numElem)
if self.stackMin.isEmpty():
self.stackMin.push(numElem)
elif numElem <= self.getMin():
self.stackMin.push(numElem)
else:
self.stackMin.push(self.getMin())
def pop(self):
value = self.stackData.pop()
self.stackMin.pop()
return value
def peek(self):
return self.stackData.peek()
def size(self):
return self.stackData.size()