力扣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();
 */
相关推荐
APIshop18 分钟前
高性能采集方案:淘宝商品 API 的并发调用与数据实时处理
linux·网络·算法
rannn_11127 分钟前
【SQL题解】力扣高频 SQL 50题|DAY5
数据库·后端·sql·leetcode·题解
松涛和鸣28 分钟前
DAY38 TCP Network Programming
linux·网络·数据库·网络协议·tcp/ip·算法
ss27332 分钟前
ThreadPoolExecutor七大核心参数:从源码看线程池的设计
java·数据库·算法
qq_4335545442 分钟前
C++ 状压DP(01矩阵约束问题)
c++·算法·矩阵
虫小宝43 分钟前
返利app排行榜系统设计:基于大数据计算的实时排名算法实现
大数据·算法
C雨后彩虹1 小时前
字符串拼接
java·数据结构·算法·华为·面试
LYFlied1 小时前
【每日算法】LeetCode 279. 完全平方数(动态规划)
前端·算法·leetcode·面试·动态规划
scx201310041 小时前
20251201换根DP总结
算法·动态规划·换根dp
zd2005721 小时前
STREAMS指南:环境及宿主相关微生物组研究中的技术报告标准
人工智能·python·算法