python2.7
思想:
入队时:判断s2是否为空,如果是,加数据追加到s1
如果s2不为空,先将s2中数据倒入s1,再将数据追加到s1
出队时:将s1中的数据倒入s2后,再从s2中弹出
#coding:utf-8
"""
两个栈实现队列
"""
class Queue(object):
def __init__(self):
self.s1 = []
self.s2 = []
#定义入队列
def inqueue(self,data):
#如果s2为空直接压入s1,1,2,3,4,5
if self.s2 == []:
self.s1.append(data)
print(data,'-----in')
#如果s2不为空,将s2数据压入s1,(5-4)--->(4,5)
#再将数据压入s1(4,5)-->(4,5,6)
else:
while self.s2:
self.s1.append(self.s2.pop())
self.s1.append(data)
print(data,'------in')
#定义出队列
def outqueue(self):
while self.s1:
self.s2.append(self.s1.pop())
try:
return self.s2.pop()
except:
print('empty')
if __name__ == '__main__':
queue = Queue()
queue.inqueue(0)
queue.inqueue(1)
queue.inqueue(2)
queue.inqueue(3)
queue.inqueue(4)
print(queue.outqueue())
print(queue.outqueue())
print(queue.outqueue())
#print(queue.outqueue())
#print(queue.outqueue())
queue.inqueue(5)
queue.inqueue(6)
queue.inqueue(7)
queue.inqueue(8)
print(queue.outqueue())
print(queue.outqueue())
print(queue.outqueue())
print(queue.outqueue())
print(queue.outqueue())
print(queue.outqueue())
print(queue.outqueue())