当前位置:网站首页>用栈实现队列(双栈,输入栈、输出栈)
用栈实现队列(双栈,输入栈、输出栈)
2022-04-22 08:17:00 【学海无涯苦作舟呀】
题目链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
题目:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false。
解题思路:将一个栈当作输入栈,用于push 传入的数据;另一个栈当作输出栈,用于pop 和peek 操作。
每次pop或peek时,若输出栈为空则将输入栈的全部数据依次push进输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序(实现反转)。
代码如下:
class MyQueue {
Deque<Integer> inStack;
Deque<Integer> outStack;
public MyQueue() {
inStack = new ArrayDeque<Integer>();
outStack = new ArrayDeque<Integer>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if (outStack.isEmpty()) {
outStack_isEmpty();//将输入栈的全部数据依次push进输出栈
}
return outStack.pop();
}
public int peek() {
if (outStack.isEmpty()) {
//peek和pop同理
outStack_isEmpty();
}
return outStack.peek();
}
public boolean empty() {
//instack和outstack都有队列数据
return inStack.isEmpty() && outStack.isEmpty();
}
private void outStack_isEmpty() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
}
版权声明
本文为[学海无涯苦作舟呀]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_46184836/article/details/124291674
边栏推荐
猜你喜欢
随机推荐
Py skill tree
Rhel7 logical volume management - Notes
Introduction to Nessus vulnerability scanning
C语言如何设置随机数
goto Statement
require-dev.mikey179/vfsStream is invalid, it should not contain uppercase characters. Please use m
How to set random number in C language
RHCSA第三天作业
变量的作用域和生命周期
【微信小程序】为小程序设置底部菜单(tabBar)
@ scheduled cron expression in quartz
如何清空输入缓冲区
The essence of array parameters
初识C语言~循环语句
What are the common collections?
Hyperledger Fabric1. 4 environment construction and example test
Operation steps for mysqlbin log playback
Solution access denied for user 'root' @ 'localhost' (using password: yes)
Restore MySQL service after computer reset
TypeScript(1)








