当前位置:网站首页>利用栈实现队列的出队入队
利用栈实现队列的出队入队
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
边栏推荐
猜你喜欢
Winter combat camp hands-on combat - MySQL database rapid deployment practice lead mouse cloud Xiaobao
阿里矢量库的图标使用教程(在线,下载)
Dolphinscheduler配置Datax踩坑记录
Practice using polardb and ECs to build portal websites
OVS and OVS + dpdk architecture analysis
qs.stringify 接口里把入参转为&连接的字符串(配合application/x-www-form-urlencoded请求头)
双指针仪表盘读数(一)
BPF program of type XDP
Thanos Compactor组件使用
Detailed explanation of RDMA programming
随机推荐
Abnormal record-21
Abnormal record-17
oracle 修改默认临时表空间
Static interface method calls are not supported at language level ‘5‘ 异常解决
select命令产生redo日志问题的分析
Winter combat camp hands-on combat - MySQL database rapid deployment practice lead mouse cloud Xiaobao
qs.stringify 接口里把入参转为&连接的字符串(配合application/x-www-form-urlencoded请求头)
Build a cloud blog based on ECS (send blessings on the cloud Xiaobao code and draw iphone13 for free)
prometheus告警记录持久化(历史告警保存与统计)
js 函数包裹forEach中使用return跳不出外层函数
oracle分区的相关操作
Research on alertmanager repeated / missing alarm phenomenon and two key parameters_ Wait and group_ Interpretation of interval
解决:You have 18 unapplied migration(s). Your project may not work properly until you apply
Oracle和mysql批量查询用户下所有表名和表名注释
oracle表空间表分区详解及oracle表分区查询使用方法
RAC环境集群组件gipc无法正确识别心跳网络状态问题分析
PG SQL截取字符串到指定字符位置
JS format current time and date calculation
error 403 In most cases, you or one of your dependencies are requesting解决
Prometheus Thanos快速指南