美文网首页
模拟题 02 用栈实现队列

模拟题 02 用栈实现队列

作者: 格林哈 | 来源:发表于2020-08-06 08:53 被阅读0次
  • 思路
    • 两个栈,入队一直用第一个栈,出队,把第一个栈数据倒转到第二栈,第二个栈的基本操作,就跟队列基本操作一致。
  • 代码
public  class MyQueue {
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.push(1);
        myQueue.push(2);
        myQueue.push(3);
        myQueue.push(4);
        myQueue.push(5);
        while (!myQueue.empty()) {
            System.out.println(myQueue.pop());
        }
    }
        Stack<Integer> stackIn= new Stack<>();;
        Stack<Integer>stackIn2 =new Stack<>();
        /** Initialize your data structure here. */
        public MyQueue() {
        }

        /** Push element x to the back of queue. */
        public void push(int x) {
            if(stackIn.isEmpty()) {
                while (!stackIn2.isEmpty()) {
                    stackIn.push(stackIn2.pop());
                }
            }
            stackIn.push(x);
        }

        /** Removes the element from in front of queue and returns that element. */
        public int pop() {

            if(stackIn2.isEmpty()) {
                while (!stackIn.isEmpty()) {
                    stackIn2.push(stackIn.pop());
                }
            }
            return stackIn2.pop();
        }

        /** Get the front element. 改进 */
        public int peek() {
            if(stackIn2.isEmpty()) {
                while (!stackIn.isEmpty()) {
                    stackIn2.push(stackIn.pop());
                }
            }
            return stackIn2.peek();
        }

        /** Returns whether the queue is empty. */
        public boolean empty() {
            if(stackIn.isEmpty() && stackIn2.isEmpty()) {
                return true;
            }
            return false;
        }
}

相关文章

  • 模拟题 02 用栈实现队列

    思路两个栈,入队一直用第一个栈,出队,把第一个栈数据倒转到第二栈,第二个栈的基本操作,就跟队列基本操作一致。 代码

  • 数据结构——栈和队列

    用数组实现栈和队列 用栈实现队列 用队列实现栈 栈和队列的经典算法题最小间距栈宠物收养所 数组实现栈和队列 用数组...

  • leecode刷题(26)-- 用栈实现队列

    leecode刷题(26)-- 用栈实现队列 用栈实现队列 使用栈实现队列的下列操作: push(x) -- 将一...

  • C语言第七次作业:链表

    707. 设计链表 空指针 空节点 225. 用队列实现栈 链式存储栈 双队列实现栈 232. 用栈实现队列 链式...

  • 队列之-队列实现栈

    一、队列实现栈核心算法概述 之前已经描述过了用栈实现队列的功能,见栈系列之-实现队列,那么同样队列也可以用来实现栈...

  • 38_两个有趣的问题

    关键词:通过栈实现队列、通过队列实现栈 0. 通过栈实现队列 用栈实现队列等价于用后进先出的特性实现先进先出的特性...

  • 栈&队列

    一、栈&队列总结 栈/队列的应用接雨水验证栈序列滑动窗口的最大值 栈/队列的特殊实现用两个栈实现队列用两个队列实现...

  • 面试题9: 用两个栈实现队列

    9-1 用两个栈实现队列 9-2 用两个队列实现栈

  • LeetCode 每日一题 [12] 用队列实现栈

    LeetCode 用队列实现栈 [简单] 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈pop(...

  • Python学习教程:用队列实现栈

    接着上一期跟大家说的用栈实现队列,这期的Python学习教程跟大家讲用队列实现栈 题目:使用队列实现栈的下列操作:...

网友评论

      本文标题:模拟题 02 用栈实现队列

      本文链接:https://www.haomeiwen.com/subject/xthdrktx.html