力扣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();
 */
相关推荐
꧁细听勿语情꧂9 分钟前
数据结构概念和算法、时间复杂度、空间复杂度引入
c语言·开发语言·数据结构·算法
Felven20 分钟前
B. The 67th 6-7 Integer Problem
数据结构·算法
玉树临风ives21 分钟前
atcoder ABC 454 题解
算法·深度优先·图论
钮钴禄·爱因斯晨29 分钟前
聚焦操作系统中的PV操作
数据库·算法·系统架构·c#
云泽80835 分钟前
笔试算法 - 双指针篇(一):移动零、复写零、快乐数与盛水容器
c++·算法
不才小强1 小时前
目标跟踪算法DeepSort实战
人工智能·算法·目标跟踪
papership1 小时前
【入门级-数学与其他:1.数及其运算:进制与进制转换:二进制、八进制、十进制、十六进制】
算法
ComputerInBook1 小时前
数字图像处理(4版)——第 4 章——频域滤波(下)(Rafael C.Gonzalez&Richard E. Woods)
人工智能·算法·计算机视觉·频域滤波
会编程的土豆1 小时前
【复习】二分查找
数据结构·c++·算法
Yzzz-F2 小时前
Problem - D - Codeforces
算法