当前位置:网站首页>用栈实现队列
用栈实现队列
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
边栏推荐
- IText 7 generate PDF summary
- 异常:IOException:Stream Closed
- Database operation of tyut Taiyuan University of technology 2022 database
- Differences and application scenarios between MySQL index clock B-tree, b+tree and hash indexes
- Tyut outline of 2022 database examination of Taiyuan University of Technology
- C code implementation of robust estimation in rtklib's pntpos function (standard single point positioning spp)
- 4.30动态内存分配笔记
- Small exercise of library management system
- Edit distance (multi-source BFS)
- Summary of multiple choice questions in the 2022 database of tyut Taiyuan University of Technology
猜你喜欢

系统设计学习(三)Design Amazon‘s sales rank by category feature

记录:初次cmd启动MySQL拒接访问之解决

染色法判定二分图

Alibaba cloud microservices (IV) service mesh overview and instance istio

The earth revolves around the sun
![[dry goods] cycle slip detection of suggestions to improve the fixed rate of RTK ambiguity](/img/9d/7284c1399964d3fb48886f12e4941c.jpg)
[dry goods] cycle slip detection of suggestions to improve the fixed rate of RTK ambiguity

面试必备:聊聊分布式锁的多种实现!

Detailed explanation of balanced binary tree is easy to understand

Differences and application scenarios between MySQL index clock B-tree, b+tree and hash indexes

国企秋招经验总结
随机推荐
System design learning (III) design Amazon's sales rank by category feature
MySQL 30000 word essence summary + 100 interview questions, hanging the interviewer is more than enough (Collection Series
Small exercise of library management system
[GNSS] robust estimation (robust estimation) principle and program implementation
架构师怎样绘制系统架构蓝图?
国企秋招经验总结
Employment of cashier [differential constraint]
Database operation of tyut Taiyuan University of technology 2022 database
几道高频的JVM面试题
Differences and application scenarios between MySQL index clock B-tree, b+tree and hash indexes
面渣逆袭:Redis连环五十二问,三万字+八十图详解。
TYUT太原理工大学2022数据库考试题型大纲
十分钟彻底掌握缓存击穿、缓存穿透、缓存雪崩
RTKLIB: demo5 b34f. 1 vs b33
错误: 找不到符号
Pride-pppar source code analysis
One article to get UDP and TCP high-frequency interview questions!
Chromatic judgement bipartite graph
4.30动态内存分配笔记
MySQL Database Constraints