使用两个队列实现堆栈 [英] Implement Stack using Two Queues

查看:129
本文介绍了使用两个队列实现堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前有一个类似的问题,但这里的问题与之相反,使用两个队列作为堆栈。问题...

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

给定两个具有标准操作的队列( enqueue dequeue isempty size ),实现其标准操作的堆栈( pop push isempty size )。

Given two queues with their standard operations (enqueue, dequeue, isempty, size), implement a stack with its standard operations (pop, push, isempty, size).

解决方案应该有两个版本。


  • 版本 A :推送项目时堆栈应该是高效的;和

  • 版本 B :弹出一个项目时,堆栈应该是高效的。

  • Version A: The stack should be efficient when pushing an item; and
  • Version B: The stack should be efficient when popping an item.

我比任何特定语言实现对算法感兴趣。不过,我欢迎我熟悉的语言表达方式( java c# python javascript php )。

I am interested in the algorithm more than any specific language implementations. However, I welcome solutions expressed in languages which I am familiar (java,c#,python,vb,javascript,php).

推荐答案

版本A(高效推送):


  • push:


    • 队列中的入队


    • 而queue1的大小大于1,管出列项从queue1到queue2

    • 出队并返回队列1的最后一个项目,然后切换queue1和queue2的名称

    版本B(高效弹出):


    • push:


      • 在队列2中排队

      • 将queue1中的所有项目排入队列2,然后切换queue1和queue2的名称


      • deqeue from queue1

      这篇关于使用两个队列实现堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆