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

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

问题描述

一个类似的问题被问早前的,但这里的问题是它的反向使用两个队列作为堆栈。现在的问题...

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

由于两个队列与他们的标准操作(排队离队的isEmpty 尺寸的),实施堆栈与它的标准操作(流行的isEmpty 尺寸的)。

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

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

There should be TWO versions of the solution.

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

我感兴趣的算法比任何具体的语言实现研究。不过,我欢迎的解决方案pssed中,我熟悉(Java和C#,Python和VB,JavaScript的,PHP)的语言EX $ P $。

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版:

  • 推:
    • 在排队的队列1
    • push:
      • enqueue in queue1
      • 而队列1的大小大于1,出列管项目从队列1到队列2
      • 离队,并返回队列1的最后一个项目,然后切换队列1和队列2的名称

      版本B:

      • 推:
        • 在排队的队列2
        • 在排队队列1在队列2中的所有项目,然后切换队列1和队列2的名称
        • push:
          • enqueue in queue2
          • enqueue all items of queue1 in queue2, then switch the names of queue1 and queue2
          • 从队列1 deqeue

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

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