力扣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();
 */
相关推荐
青少儿编程课堂3 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z3 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
AIHR数智引擎3 小时前
AI原生组织,转型的关键是体系化能力重构
人工智能·经验分享·职场和发展·重构·ai-native
JianZhen✓3 小时前
后端进阶 13 问:CI/CD、Prisma、ORM、ER 图、SSE、索引事务、Nest 生命周期一次讲透(附面试答法)
ci/cd·面试·职场和发展
geovindu3 小时前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥4 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
AAA修煤气灶刘哥5 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
电科_银尘6 小时前
【大模型算法与工程 34】QLoRA:量化底座上的低秩训练
人工智能·算法·机器学习
专注仿真6 小时前
智能体训练:模仿学习与 MCTS 算法详解与实战
算法·强化学习·仿真·afsim智能体·仿真训练
是main不是漫16 小时前
【快慢指针 | LeetCode202 快乐数】鸽巢原理佐证环特性,快慢指针巧解快乐数
c语言·开发语言·c++·算法