LeetCode 232题用栈实现队列(Implement Queue using Stacks) Java语言求解
题目链接
https://leetcode-cn.com/problems/implement-queue-using-stacks/
题目描述
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
思路
使用两个栈来完成操作, 首先全部进入第一个栈,再全部进入第二个栈,用图来演示一下:
首先进入栈1;

然后出栈1,入栈2;


由图可以知道,用两个栈即可完成队列的操作;
分为下面三种情况
- Stack_1空,Stack_2有元素,这时push()操作让Stack_1进行push();pop()操作,只需让Stack_2进行pop();peek()操作,也只需让Stack_2进行peek()就可以了;这时队列不为空;
- Stack_1不空,Stack_2空,这时push()操作让Stack_1进行push();pop()操作需要将Stack_1的所有元素进入Stack_2,Stack_2进行pop();peek()操作,也只需要将Stack_1的所有元素进入Stack_2,再让Stack_2进行peek()就可以了;这是队列不为空;
- Stack_1空,Stack_2也为空,push()操作让Stack_1进行push()即可,pop()和push()无法完成,队为空。
代码
import java.util.Stack;
class MyQueue {
//初始化栈1和栈2
private Stack<Integer> Stack_1;
private Stack<Integer> Stack_2;
/** Initialize your data structure here. */
public MyQueue() {
Stack_1 = new Stack<>();
Stack_2 = new Stack<>();
}
//进入第一个栈
/** Push element x to the back of queue. */
public void push(int x) {
Stack_1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
//如果栈2是空的
if(Stack_2.isEmpty()){
//将栈1的所有元素入栈2
while(!Stack_1.isEmpty()){
Stack_2.push(Stack_1.pop());
}
}
if (!Stack_2.isEmpty()) {
return Stack_2.pop();
}
throw new RuntimeException("MyQueue空了!");
}
/** Get the front element. */
public int peek() {
//如果栈2是空的
if(Stack_2.isEmpty()){
//将栈1的所有元素入栈2
while(!Stack_1.isEmpty()){
Stack_2.push(Stack_1.pop());
}
}
if (!Stack_2.isEmpty()) {
return Stack_2.peek();
}
throw new RuntimeException("MyQueue空了!");
}
/** Returns whether the queue is empty. */
public boolean empty() {
return Stack_1.isEmpty() && Stack_2.isEmpty();
}
}
欢迎关注
扫下方二维码即可关注:,微信公众号:code随笔
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效