力扣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();
 */
相关推荐
珹洺1 小时前
C++从入门到实战(十)类和对象(最终部分)static成员,内部类,匿名对象与对象拷贝时的编译器优化详解
java·数据结构·c++·redis·后端·算法·链表
写bug的小屁孩1 小时前
移动零+复写零+快乐数+盛最多水的容器+有效三角形的个数
c++·算法·双指针
飞川撸码1 小时前
【LeetCode 热题100】208:实现 Trie (前缀树)(详细解析)(Go语言版)
算法·leetcode·golang·图搜索算法
这就是编程2 小时前
自回归模型的新浪潮?GPT-4o图像生成技术解析与未来展望
人工智能·算法·机器学习·数据挖掘·回归
羑悻的小杀马特2 小时前
【狂热算法篇】探寻图论幽径:Bellman - Ford 算法的浪漫征程(通俗易懂版)
c++·算法·图论·bellman_ford算法
Fantasydg6 小时前
DAY 31 leetcode 142--链表.环形链表
算法·leetcode·链表
basketball6166 小时前
C++ STL常用算法之常用排序算法
c++·算法·排序算法
moz与京6 小时前
[附C++,JS,Python题解] Leetcode 面试150题(10)——轮转数组
c++·python·leetcode
qystca6 小时前
蓝桥云客 岛屿个数
算法·dfs·bfs
什码情况7 小时前
回文时间 - 携程机试真题题解
数据结构·python·算法·华为od·机试