两队列模拟一个栈,python实现

python实现两个队列模拟一个栈:

class Queue(object):
    def __init__(self):
        self.stack1=[]
        self.stack2=[]

    def enqueue(self, item):
        if len(self.stack1) == 0:
            self.stack1.append(item)
        elif len(self.stack2) == 0:
            self.stack2.append(item)
        if len(self.stack2)==1 and len(self.stack2) >= 1:
            while len(self.stack1)>0:
                self.stack2.append(self.stack1.pop(0))
        elif len(self.stack1)==1 and len(self.stack2) >= 1:
            while len(self.stack2)>0:
                self.stack1.append(self.stack2.pop(0))

    def dequeue(self):
        if self.stack1:
            return self.stack1.pop(0)
        elif self.stack2:
            return self.stack2.pop(0)
        else:
            return None

q = Queue()
q.enqueue(3)
# print(q.dequeue())
q.enqueue(4)
q.enqueue(5)
q.enqueue(6)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())

 

posted @ 2017-12-23 22:06  老A队长  阅读(359)  评论(0编辑  收藏  举报