当前位置:网站首页>利用队列实现栈
利用队列实现栈
2022-04-23 06:05:00 【大林子先森】
实现思路:
1)准备两个队列 queue1, queue2(队列特性先进先出,栈的特性先进后出) 2)入栈时,元素依次插入到queue1中 3)出栈时,做如下处理: 3.1)如果queue2为空,则将queue1向queue2拷贝,剩最后一个元素返回 3.2)如果queue2不为空,则将queue2向queue1拷贝,剩最后一个元素返回
直接上代码:
import java.util.LinkedList;
import java.util.Queue;
/**
* @ClassName : MyStackWithQueue
* @Description: 通过队列实现栈
* @Author: liulianglin
* @Date: 2021/11/17 23:36
* @Version : 1.0
*
实现思路:
1)准备两个队列 queue1, queue2(队列特性先进先出,栈的特性先进后出)
2)入栈时,元素依次插入到queue1中
3)出栈时,做如下处理:
3.1)如果queue2为空,则将queue1向queue2拷贝,剩最后一个元素返回
3.2)如果queue2不为空,则将queue2向queue1拷贝,剩最后一个元素返回
*/
public class MyStackWithQueue {
private Queue<Integer> queue1 = new LinkedList<>();
private Queue<Integer> queue2 = new LinkedList<>();
/**
* 插入
* @return
*/
private boolean push(int ele){
return queue1.add(ele);
}
private Integer pop(){
if (queue2.size() == 0){
//如果queue2为空,则将queue1向queue2拷贝,剩最后一个元素返回
while (queue1.size() > 1) {
queue2.add(this.queue1.poll());
}
//返回此时queue1的最后一个元素
return this.queue1.poll();
}else{
//如果queue2不为空,则将queue2向queue1拷贝,剩最后一个元素返回
while(queue2.size() > 1){
queue1.add(this.queue2.poll());
}
return this.queue2.poll();
}
}
public static void main(String[] args) {
MyStackWithQueue myStackWithQueue = new MyStackWithQueue();
myStackWithQueue.push(1);
myStackWithQueue.push(2);
myStackWithQueue.push(3);
System.out.println(myStackWithQueue.pop());
System.out.println(myStackWithQueue.pop());
System.out.println(myStackWithQueue.pop());
}
}
版权声明
本文为[大林子先森]所创,转载请带上原文链接,感谢
https://blog.csdn.net/liulianglin/article/details/121390957
边栏推荐
- 一个DG环境的ORA-16047: DGID mismatch between destination setting and target database问题排查及监听VNCR特性
- How does thanos configure different data retention durations for different tenants
- Ali vector library Icon tutorial (online, download)
- Abnormal record-13
- OSS云存储管理实践(体验有礼)
- Dolphinscheduler配置Datax踩坑记录
- Django::Did you install mysqlclient?
- Prometheus Thanos与Cortex组件比较
- 19C RAC修改VIP及SCANIP步骤-同网段
- Apache Atlas 编译及安装记录
猜你喜欢
oracle表的约束详解
Relabel of Prometheus_ Configs and metric_ relabel_ Configs explanation and usage examples
Using Prom label proxy to implement label based multi tenant reading of Prometheus thanos
Introduction to RDMA network
Dolphinscheduler调度sql任务建表时The query did not generate a result set异常解决
阿里矢量库的图标使用教程(在线,下载)
搭建基于OSS的图片分享网站-反馈有礼
Chaos帶你快速上手混沌工程
Detailed explanation of RDMA programming
mysql和pgsql时间相关操作
随机推荐
RAC环境中openssh版本对SSH互信创建的影响
SQL中 with函数的详解与用法
Exception record-7
关于Postgres主从复制延迟监控的错误告警问题
RAC环境集群组件gpnp未启动成功问题分析
【机器学习】笔记 4、KNN+交叉验证
Oracle Job定时任务的使用详解
RAC环境数据库节点参数设置不当导致监听无法连接问题排查
Thanos如何为不同租户配置不同的数据保留时长
OVS and OVS + dpdk architecture analysis
异常记录-18
常用于融合去重的窗口函数row_number
Exception record-6
阿里矢量库的图标使用教程(在线,下载)
Build an OSS based image sharing website - polite feedback
实践使用PolarDB和ECS搭建门户网站
19C RAC修改VIP及SCANIP步骤-同网段
RAC环境alert日志报错Drop transient type: SYSTP2JW0acnAurDgU1sBqMBryw==的排查
发布自定义插件到本地服务器
oracle创建表空间和修改用户默认表空间