python2.7
思想:
入栈:如果队列q2为空,将数据追加到q1
如果队列q2不为空,先将q2中数据从首部弹出追加到q1中,再将数据追加入q1
出栈:
先将s1中数据从首部弹出追加到s2中,在从s2中从尾部弹出
#coding:utf-8
class Stack(object):
def __init__(self):
self.q1 = []
self.q2 = []
#入栈
def instack(self,data):
while self.q2:
self.q1.append(self.q2.pop(0))
self.q1.append(data)
print('------',data)
#出栈
def outstack(self):
while self.q1:
self.q2.append(self.q1.pop(0))
try:
return self.q2.pop()
except:
print('empty')
if __name__ == '__main__':
stack = Stack()
stack.instack(0)
stack.instack(1)
stack.instack(2)
stack.instack(3)
stack.instack(4)
print(stack.outstack())
print(stack.outstack())
print(stack.outstack())
stack.instack(5)
stack.instack(6)
stack.instack(7)
stack.instack(8)
print(stack.outstack())
print(stack.outstack())
print(stack.outstack())
print(stack.outstack())
print(stack.outstack())
print(stack.outstack())
print(stack.outstack())