当前位置:网站首页>利用栈实现队列的出队入队
利用栈实现队列的出队入队
2022-04-23 06:05:00 【大林子先森】
* 实现思路: * * 1)准备两个栈stack1和stack2 * 2)入队列时,数据先向stack1中push * 3)出队列时,先判断stack2是否是空的, * 3.1)如果是空的就将stack1中的元素依次向stack2中push(直至stack1为空),然后从stack2中弹出一个元素返回 * 3.2)如果不是空的,说明stack1中的数据全部转到了stack2,直接从stack2中返回。 * 后续插入直接插入到stack1中,当stack2中的元素空了之后,再将stack1中的元素全部放入stack2中。以此循环往复,实现FIFO效果 *
上rehuhu的代码!!
package com.lll.algorithms.collection.queue;
import java.util.Stack;
/**
* @ClassName : MyQueueWithStack
* @Description: 利用栈实现队列的出队入队
* @Author: liulianglin
* @Date: 2021/10/14 15:17
* @Version : 1.0
*
* 实现思路:
*
* 1)准备两个栈stack1和stack2
* 2)入队列时,数据先向stack1中push
* 3)出队列时,先判断stack2是否是空的,
* 3.1)如果是空的就将stack1中的元素依次向stack2中push(直至stack1为空),然后从stack2中弹出一个元素返回
* 3.2)如果不是空的,说明stack1中的数据全部转到了stack2,直接从stack2中返回。
* 后续插入直接插入到stack1中,当stack2中的元素空了之后,再将stack1中的元素全部放入stack2中。以此循环往复,实现FIFO效果
*
*/
public class MyQueueWithStack<T> {
private Stack<T> stack1 = new Stack<>();
private Stack<T> stack2 = new Stack<>();
public boolean mpush(T t){
return stack1.push(t)==null ? false:true;
}
public T mpop(){
if (stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public static void main(String[] args) {
MyQueueWithStack<Integer> myQueueWithStack = new MyQueueWithStack<>();
myQueueWithStack.mpush(1);
myQueueWithStack.mpush(3);
myQueueWithStack.mpush(9);
System.out.println(myQueueWithStack.mpop());
System.out.println(myQueueWithStack.mpop());
System.out.println(myQueueWithStack.mpop());
}
}
版权声明
本文为[大林子先森]所创,转载请带上原文链接,感谢
https://blog.csdn.net/liulianglin/article/details/121390644
边栏推荐
猜你喜欢

Prometheus cortex Architecture Overview (horizontally scalable, highly available, multi tenant, long-term storage)

Problems related to Prometheus cortex using block storage

Chaos帶你快速上手混沌工程

oracle表的约束详解

Thanos compact component test summary (processing historical data)

Relabel of Prometheus_ Configs and metric_ relabel_ Configs explanation and usage examples

窗口分析函数LAST_VALUE,FIRST_VALUE,lag,lead

Chaos vous emmène au projet chaos.

【机器学习】笔记 4、KNN+交叉验证

Dolphinscheduler集成Flink任务踩坑记录
随机推荐
Oracle Job定时任务的使用详解
Thanos compact component test summary (processing historical data)
异常记录-12
BPF program of type XDP
oracle通过触发器和序列来定义自增主键,并且设置定时任务每秒钟插入一条数据到目标表
微服务架构核心概念
RAC环境数据库节点参数设置不当导致监听无法连接问题排查
19C环境ORA-01035登陆报错处理
Prometheus Thanos快速指南
js 函数包裹forEach中使用return跳不出外层函数
oracle 修改默认临时表空间
Practice using polardb and ECs to build portal websites
冬季实战营 动手实战-MySQL数据库快速部署实践 领鼠标 云小宝
pg库查看某模式下某表的分布键
异常记录-11
Typical application scenarios of alicloud log service SLS
VirtualBox如何修改“网络地址转换(NAT)”网络模式下分配给虚拟机的IP网段
Chaos takes you to the chaos project quickly
Oracle redo log产生量大的查找思路与案例
Apache Atlas 编译及安装记录