力扣232. 用栈实现队列(两栈实现队列)

Problem: 232. 用栈实现队列

文章目录

题目描述

思路

利用两个栈,一个入栈一个出栈搭配着实现队列的相关操作:

1.创建两个栈stack1和stack2;

2.void push(int x) :将要入队的元素先入栈stack1;

3.int pop() :当stack2为空时并且stack1不为空时将stack1中的元素均弹出并同时依次入栈stack2,最后将stack2的栈顶元素弹出

4.int peek() :同理pop;

5.boolean empty():只用两个栈均为空时才返回true

Code

java 复制代码
class MyQueue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    /**
     * Push the element to the stack1
     *
     * @param x The element to be pushed
     */
    public void push(int x) {
        stack1.push(x);
    }

    /**
     * Pop the top element of stack2
     *
     * @return int
     */
    public int pop() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    /**
     * Peek the top element of stack2
     *
     * @return int
     */
    public int peek() {
        if (stack2.isEmpty()) {
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
            }
        }
        return stack2.peek();
    }

    /**
     * Check the empty of myQueue
     *
     * @return boolean
     */
    public boolean empty() {
        if (stack1.empty() && stack2.isEmpty()) {
            return true;
        }
        return false;
    }
}
/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
相关推荐
Eric.Lee202123 分钟前
数据集-目标检测系列- 螃蟹 检测数据集 crab >> DataBall
python·深度学习·算法·目标检测·计算机视觉·数据集·螃蟹检测
夜流冰29 分钟前
工具方法 - 面试中回答问题的技巧
面试·职场和发展
林辞忧32 分钟前
算法修炼之路之滑动窗口
算法
￴ㅤ￴￴ㅤ9527超级帅43 分钟前
LeetCode hot100---二叉树专题(C++语言)
c++·算法·leetcode
liuyang-neu44 分钟前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先
一个不知名程序员www1 小时前
leetcode面试题17.04:消失的数字(C语言版)
leetcode
penguin_bark1 小时前
LCR 068. 搜索插入位置
算法·leetcode·职场和发展
_GR1 小时前
每日OJ题_牛客_牛牛冲钻五_模拟_C++_Java
java·数据结构·c++·算法·动态规划
ROBIN__dyc1 小时前
表达式
算法
无限大.1 小时前
c语言实例
c语言·数据结构·算法