两个栈实现一个队列

本文介绍了一种使用两个栈来模拟队列操作的方法。通过在第一个栈中压入元素,在需要弹出时将第一个栈的所有元素依次弹出并压入第二个栈,再从第二个栈中弹出元素,以此实现先进先出的队列特性。
class Two_stacks(object):
    def __init__(self):
        self._oneli=[]
        self._twoli=[]
    def entrance(self,item):
        """栈结构模拟进入队列"""
        self._oneli.append(item)
    def popup(self):
        """栈结构模拟弹出队列"""
        if self._twoli:
            # 如果第二个栈结构存在值就直接弹出
            return self._twoli.pop()
        else:
            # 如果不存在,将第一个栈循环从队尾弹出进入第二个栈的栈底
            if self._oneli:
                while self._oneli:
                    self._twoli.append(self._oneli.pop())
                return  self._twoli.pop()
            else:
            # 如果第一个栈内不存在值,直接返回空
                return None
if __name__ == '__main__':
    queue=Two_stacks()
    queue.entrance(1)
    queue.entrance(2)
    queue.entrance(3)
    queue.entrance(4)
    queue.entrance(5)
    print(queue.popup())
    print(queue.popup())
    print(queue.popup())
    print(queue.popup())
    print(queue.popup())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值