当前位置:网站首页>用栈模拟队列
用栈模拟队列
2022-08-08 06:28:00 【记得爱蓝色】
队列的特点是:先进先出(FIFO),栈的特点是后进先出(LIFO),如果要实现用栈来模拟队列的出队入队操作,则需要两个栈:入队栈(in)和出队栈(out)。

要模拟队列的入队和出队操作首先我们要定义两个栈:in用来入队,out来进行出队操作。
进行入队操作:
先将入队的元素存入入队栈(in)中使用栈的push()方法,这样最后存入的元素就成为了栈顶
进行出队操作:
将入队栈(in)中的元素在存入出队栈中,这样入队栈(in)中的栈顶就成了出队栈中的栈底,在使用pop()方法出栈,就实现了队列的先进先出。
注意:
我们在进行入队操作时,先要对出队栈(out)是否为空,如果为空便可以直接进行入栈操作,如果不为空,则要把出队栈(out)中的元素压入in中,在进行添加新元素。同理在进行出队操作时也要判断入队栈(in)是否为空,如果为空直接进行出栈操作,如果不为空,则把入队栈(in)中的元素存放在出队栈(out)中,在进行出队操作。
代码实现:
package com.yx.demo07;
import java.util.Stack;
public class Test01 {
public static void main(String[] args) {
MyQueue<String> queue = new MyQueue<String>();
queue.offer("A1");
queue.offer("A2");
queue.offer("A3");
queue.offer("A4");
System.out.println(queue.poll() + ":出队");
queue.offer("A5");
//遍历队列
while(!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
//栈模拟队列
class MyQueue<E> {
private Stack<E> in = new Stack<E>(); //入队栈
private Stack<E> out = new Stack<E>(); //出队栈
//判断队列是否为空
public boolean isEmpty() {
return in.size() == 0 && out.size() == 0;
}
//入队
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();
}
}边栏推荐
- Folder permission configuration for Unity local IIS service construction
- Day38------网络相关
- By using the fgets () the number of rows in the statistics file and use the fgets ()/fputs () copy files
- The state machine control shift register multisim simulation in the process of state variables and state transition conditions don't match
- 反射,魔法方法,元类相关知识点总结
- 盛水最多的容器
- Binary tree traversal and method
- UGUI_编辑器扩展与常用优化
- Unity_滑动面板(滚动面板) + UI动画
- Writing of Makefile (detailed example)
猜你喜欢

NVIDIA CUDA Highly Parallel Processor Programming (6): Parallel Mode: Convolution

Math工具类的ceil()、floor()、round()方法源码阅读

acwing 63rd weekly match【2022.08.06】

【图形学】13 UnityShader语义(一)
![[Unity] 自定义日志系统 解决Unity Log的痛点](/img/2e/761761882b64dbf67418542fb21833.png)
[Unity] 自定义日志系统 解决Unity Log的痛点

关于在finally代码块中修改try代码块中基本数据类型返回值的问题

Nine common interfaces for implementing sequence table in C language

tcpdump进行IP抓包

实现字符串转换为整数(atoi)

Unity object color gradient effect (judgment logic implementation)
随机推荐
【Android安全】priv-app 系统应用权限
软件工具 | 04.Typora搭配PicGo-Core实现用时间命名图片
golang 服务诡异499、504网络故障排查
Double week leetcode 84th game
MySQL的DDL和DML
Nine common interfaces for implementing sequence table in C language
【图形学】01 数学部分(一、集合和三角函数)
leetcode daily question 8.6 (continuously updated)
自定义类加载器
【图形学】04 数学部分(四、放射变换)
诡异的druid链接池链接断开故障经验总结
基于FTP协议的文件上传与下载
TCP和UDP协议,socket套接字,半连接池,粘包问题的处理措施
关于单例模式
Binary tree traversal and method
Unity—ParticleSystem(粒子系统)与Animator(动画状态机)批量管理器
HDU 6029 个人分析
Unity_组件自动绑定
[Unity] GPU动画实现(三)——材质合并
minikube addons enable ingress 启动错误