当前位置:网站首页>用栈实现队列
用栈实现队列
2022-07-06 09:19:00 【[email protected]】
实现思路:
队列是先进先出(FIFO)
栈是后进先出(LIFO)
需要用两个栈来实现队列的先进先出
栈in实现push操作 栈out实现pop操作
我们push数据时先进的数据会被压入栈底,当我们重新把push进栈in的数据一个一个pop进栈out时,栈in底的元素此刻就成为了栈out顶部元素,所以pop数据时我们只需要pop栈out中的数据即完成队列的先进先出(FIFO)
入队时我们需要判断栈out是否为空,如果不为空,则需要pop栈out中的数据,如果为空,全部push进栈in
出队时我们需要判断栈in是否为空,如果不为空,则需要pop栈in中的数据,如果为空,全部push进栈out
具体代码如下:
//栈模拟队列
class MyQueue<E>{
public Stack<E> in = new Stack<E>(); // 入队栈
public Stack<E> out = new Stack<E>();// 出队栈
// 入队
public void offer(E e) {
while(!out.isEmpty()) {
in.push(out.pop());
}
in.push(e);
}
// 出队
public E poll() {
while(!in.isEmpty()) {
out.push(in.pop());
}
return out.pop();
}
}
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_49194330/article/details/124736851
边栏推荐
- [algorithm] sword finger offer2 golang interview question 8: the shortest subarray with a sum greater than or equal to K
- Redis介绍与使用
- Usage differences between isempty and isblank
- Implementation of Excel import and export functions
- 初识指针笔记
- 记录:newInstance()过时的代替方法
- 记录:Navicat Premium初次无法连接数据库MySQL之解决
- Heap sort [handwritten small root heap]
- IPv6 experiment
- [dry goods] cycle slip detection of suggestions to improve the fixed rate of RTK ambiguity
猜你喜欢
![[algorithm] sword finger offer2 golang interview question 3: the number of 1 in the binary form of the first n numbers](/img/64/0f352232359c7d44f12b20a64c7bb4.png)
[algorithm] sword finger offer2 golang interview question 3: the number of 1 in the binary form of the first n numbers

抽象类和接口

Dark chain lock (lca+ difference on tree)

架构师怎样绘制系统架构蓝图?
![[algorithm] sword finger offer2 golang interview question 10: subarray with sum K](/img/63/7422489d09a64ec9f0e79378761bf1.png)
[algorithm] sword finger offer2 golang interview question 10: subarray with sum K

Problems and solutions of robust estimation in rtklib single point location spp

十分鐘徹底掌握緩存擊穿、緩存穿透、緩存雪崩

View UI Plus 发布 1.3.0 版本,新增 Space、$ImagePreview 组件

Introduction and use of redis

One article to get UDP and TCP high-frequency interview questions!
随机推荐
2-year experience summary, tell you how to do a good job in project management
[untitled]
Music playback (toggle & playerprefs)
Application architecture of large live broadcast platform
How to ensure data consistency between MySQL and redis?
System design learning (III) design Amazon's sales rank by category feature
继承和多态(上)
[while your roommate plays games, let's see a problem]
Redis介绍与使用
One article to get UDP and TCP high-frequency interview questions!
一文搞定 UDP 和 TCP 高频面试题!
13 power map
MySQL backup -- common errors in xtrabackup backup
[Topic terminator]
阿里云一面:并发场景下的底层细节 - 伪共享问题
Error: symbol not found
Iterable、Collection、List 的常见方法签名以及含义
[algorithm] sword finger offer2 golang interview question 6: sum of two numbers in the sorting array
Novatel board oem617d configuration step record
Inheritance and polymorphism (I)