力扣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();
 */
相关推荐
一匹电信狗5 小时前
【LeetCode_547_990】并查集的应用——省份数量 + 等式方程的可满足性
c++·算法·leetcode·职场和发展·stl
鱼跃鹰飞5 小时前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
梵刹古音6 小时前
【C语言】 函数基础与定义
c语言·开发语言·算法
筵陌7 小时前
算法:模拟
算法
We་ct7 小时前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
renhongxia17 小时前
AI算法实战:逻辑回归在风控场景中的应用
人工智能·深度学习·算法·机器学习·信息可视化·语言模型·逻辑回归
CoderCodingNo7 小时前
【GESP】C++四级/五级练习题 luogu-P1223 排队接水
开发语言·c++·算法
民乐团扒谱机7 小时前
【AI笔记】精密光时频传递技术核心内容总结
人工智能·算法·光学频率梳
CoderCodingNo8 小时前
【GESP】C++五级/四级练习题 luogu-P1413 坚果保龄球
开发语言·c++·算法
2301_822366358 小时前
C++中的命令模式变体
开发语言·c++·算法