python ——两个队列实现一个栈&两个栈实现一个队列

1、两个队列实现一个栈

进栈:元素入队列A

出栈:判断如果队列A只有一个元素,则直接出队。否则,把队A中的元素出队并入队B,直到队A中只有一个元素,再直接出队。为了下一次继续操作,互换队A和队B。

python实现如下:

class StackWithTwoQueues(object):
    #定义两个空队列
    def __init__(self):
        self.queue1 = []
        self.queue2 = []
    #入栈
    def push(self, item):
        self.queue1.append(item)
    #出栈
    def pop(self):
        if len(self.queue1) == 0:
            return(None)
        while(len(self.queue1) != 1):
            self.queue2.append(self.queue1.pop(0))
        self.queue1, self.queue2 = self.queue2, self.queue1
        return (self.queue2.pop())
#test
if __name__ == '__main__':
    ss = StackWithTwoQueues()
    list = [0, 1, 2, 3, 4]
    for i in range(5):
        ss.push(list[i])
    print(list)
    for i in range(5):
        print(ss.pop(), ',', end = '')
#output
#[0, 1, 2, 3, 4]
#4, 3, 2, 1, 0

2、两个栈实现一个队列

入队:元素进栈A

出队:先判断栈B是否为空,为空则将栈A中的元素 pop 出来并 push 进栈B,再栈B出栈,如不为空则栈B直接出栈。

python实现如下:

class QueueWithTwoStacks(object):
    #定义两个空栈
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    #入队
    def enqueue(self, item):
        self.stack1.append(item)
    #出队
    def dequeue(self):
        if self.stack2:
            return(self.stack2.pop())
        else:
            if self.stack1 != []:
                while(self.stack1):
                    self.stack2.append(self.stack1.pop())
                return(self.stack2.pop())
            else:
                return(None)
# test
if __name__ == '__main__':
    qq = QueueWithTwoStacks()
    list = [0, 1, 2, 3, 4]
    for i in range(5):
        qq.enqueue(list[i])
    print(list)
    for i in range(5):
        print(qq.dequeue(), ',', end='')
#output
#[0, 1, 2, 3, 4]
#0, 1, 2, 3, 4, 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值