程序员代码面试指南 python实现(第一章 栈和队列:由两个栈组成队列)
程序员代码面试指南 python实现(第一章 栈和队列)
由两个栈组成队列
题目描述
解答
注意
源码
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 empty1")
return self.item.pop()
def peek(self):
if self.isEmpty():
raise Exception("Your stack is empty!")
return self.item[len(self.item)-1]
def size(self):
return len(self.item)
class TwoStackQuere(object):
def __init__(self):
self.stackPush = stack()
self.stackPop = stack()
def add(self,numElem):
self.stackPush.push(numElem)
def poll(self):
if self.stackPush.isEmpty() and self.stackPop.isEmpty():
raise Exception("your Quere is empty!")
elif self.stackPop.isEmpty():
while(self.stackPush.isEmpty() != True):
self.stackPop.push(self.stackPush.pop())
return self.stackPop.pop()
def peek(self):
if self.stackPush.isEmpty() and self.stackPop.isEmpty():
raise Exception("Your Queue is empty!")
elif self.stackPop.isEmpty():
while (self.stackPush.isEmpty() != True):
self.stackPop.push(self.stackPush.pop())
return self.stackPop.peek()
def isEmpty(self):
return self.stackPush.isEmpty() and self.stackPop.isEmpty()
def size(self):
return self.stackPush.size()