python 两个中文队列比较_详解两个队列实现一个栈(python实现——经典面试题)...

1、任务详解

使用两个队列数据结构实现一个栈,要求实现栈的出栈和进栈操作。

2、解题思路

push()操作:

为了保证先进栈的元素一直在栈底,需要将两个队列交替使用,才能满足需求。因此,想法是,我们只在空的那个队列上添加元素,然后把非空的那个队列中的元素全部追加到当前这个队列。这样一来,我们又得到一个空的队列,供下一次添加元素。

pop()操作:

因为在添加元素时,我们已经按照进栈的先后顺序把后进栈的元素放在一个队列的头部,所以出栈操作时,我们只需要找到那个非空的队列,并依次取出数据即可。

3、代码如下

class StackWithTwoQueues(object):

def __init__(self):

self._queue1 = []

self._queue2 = []

def push(self,x):

if len(self._queue1) == 0:

self._queue1.append(x)

elif len(self._queue2) == 0:

self._queue2.append(x)

if len(self._queue2) == 1 and len(self._queue1) >= 1:

while self._queue1:

self._queue2.append(self._queue1.pop(0))

elif len(self._queue1) == 1 and len(self._queue2) > 1:

while self._queue2:

self._queue1.append(self._queue2.pop(0))

def pop(self):

if self._queue1:

return self._queue1.pop(0)

elif self._queue2:

return self._queue2.pop(0)

else:

return None

def getStack(self):

print("queue1",self._queue1)

print("queue2", self._queue2)

sta = StackWithTwoQueues()

sta.push(1)

sta.getStack()

sta.push(2)

sta.getStack()

sta.push(3)

sta.getStack()

sta.push(4)

sta.getStack()

print(sta.pop())

sta.getStack()

print(sta.pop())

sta.getStack()

print(sta.pop())

sta.getStack()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值