力扣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();
 */
相关推荐
宵时待雨10 分钟前
优选算法专题6:模拟
数据结构·c++·算法·leetcode·职场和发展
Liangwei Lin15 分钟前
LeetCode 35. 搜索插入位置
数据结构·算法·leetcode
数智工坊17 分钟前
【经典RL算法】Q-Learning:强化学习的里程碑——从理论到收敛证明的完整解析
论文阅读·人工智能·深度学习·算法·transformer
叼烟扛炮19 分钟前
C++ 知识点19 匿名对象
开发语言·c++·算法·匿名对象
叼烟扛炮24 分钟前
C++ 知识点23 类模板
开发语言·c++·算法·类模版
djarmy1 小时前
C 标准库 `<stdio.h>` 完整函数清单(官方标准 + 常用全部函数)
c语言·c++·算法
七牛云行业应用1 小时前
NotebookLM 手机版上线了,这份完整指南帮你把它用起来
算法
城事漫游Molly1 小时前
定量研究设计清单:问卷、实验与变量操作化怎么做?
大数据·人工智能·算法·ai写作·论文笔记
Epiphany.5561 小时前
带依赖关系的最短路问题
算法
Kiyra1 小时前
限流不是加个计数器就行:用 Lua 脚本实现多维度原子限流
开发语言·人工智能·网络协议·职场和发展·架构·lua·ai-native