如何用栈实现队列Java(栈和队列的功能)
题目
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
来源:力扣(LeetCode)
链接:
https://leetcode-cn.com/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
/**
* https://leetcode-cn.com/problems/implement-queue-using-stacks/
*/
class MyQueue {
Deque<Integer> inStack;
Deque<Integer> outStack;
/** Initialize your data structure here. */
public MyQueue() {
inStack = new LinkedList<>();
outStack = new LinkedList<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
inStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (outStack.isEmpty()) {
inStack2outStack();
}
return outStack.pop();
}
/** Get the front element. */
public int peek() {
if (outStack.isEmpty()) {
inStack2outStack();
}
return outStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
private void inStack2outStack() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
}
总结
* 这是一个非常常见的题目,栈的特性是先入后出,队列的特性是先入先出。因此,我们可以用两个栈来实现队列,inStack记录输入,outStack记录输出,以上代码巧妙的地方是在outStack为空的时候,将inStack的数据输入进去。
- 随机文章
- 热门文章
- 热评文章
- 安卓淘宝v10.12.10.2谷歌版
- 下载利器IDM v6.41.1绿色版
- 乐秀视频编辑器 v9.7.7
- 【2022最新版】乐天产品注册和CSV批量产品编辑5分钟抓拍!
- 抖音小店和橱窗的区别 抖音小店和抖音商品橱窗的区别
- 抖音挂机的步骤,抖音挂机能挣钱是真的吗
- 抖音怎么免费看电影,不同类型的大片等你来看
- 如何快速的在抖音上删除作品,抖音上删除作品怎么删除
扫描二维码推送至手机访问。
版权声明:本文中部分文字、图片、音频、视频来源于互联网及公开渠道,仅供学习参考,版权归原创者所有! 如侵犯到您的权益,请及时通知我们!我们将在第一时间内删除。


赣公网安备36070302361030号