当前位置: 首页 > news >正文

队列OJ题——用队列实现栈

文章目录

  • 一、题目链接
  • 二、解题思路
  • 三、解题代码

一、题目链接

用队列实现栈

二、解题思路

在这里插入图片描述

三、解题代码

class MyStack {public Queue<Integer> queue1;public Queue<Integer> queue2;public int usedSize;public MyStack() {queue1  =new LinkedList<>();queue2  =new LinkedList<>();}public void push(int x) {if(!queue1.isEmpty()){queue1.offer(x);}else if(!queue2.isEmpty()){queue2.offer(x);}else{queue1.offer(x);}usedSize++;}public int pop() {//queue.size - 1 个元素if(!queue1.isEmpty()){int curSize = queue1.size();for(int i = 0; i < curSize - 1 ; i++){queue2.offer(queue1.poll());}usedSize--;return queue1.poll();}else if(!queue2.isEmpty()){int curSize = queue2.size();for(int i = 0; i < curSize - 1 ; i++){queue1.offer(queue2.poll());}usedSize--;return queue2.poll();}else{return -1;}}public int top() {if(!queue1.isEmpty()){int curSize = queue1.size();int ret = -1;for(int i = 0; i < curSize; i++){ret  = queue1.poll();queue2.offer(ret);}return ret;}else if(!queue2.isEmpty()){int curSize = queue2.size();int ret = -1;for(int i = 0; i < curSize; i++){ret  = queue2.poll();queue1.offer(ret);}return ret;}else{return -1;}}public boolean empty() {if(queue1.isEmpty() && queue2.isEmpty()){return true;}return false;}/*public boolean empty() {if(usedSize == 0){retunr true;}return false;}*/}
http://www.lryc.cn/news/438003.html

相关文章:

  • RK3588镜像打包制作,替换文件系统
  • Open-Sora代码详细解读(2):时空3D VAE
  • 基于微信平台的旅游出行必备商城小程序+ssm(lw+演示+源码+运行)
  • AI绘画:科技赋能艺术的崭新时代
  • 性能诊断的方法(四):自下而上的资源诊断方法和发散的异常信息诊断方法
  • GDPU Vue前端框架开发 计数器
  • 最大流笔记
  • el-tree父子不互相关联时,手动实现全选、反选、子级全选、清空功能
  • 模板与泛型编程笔记(一)入门篇
  • 浅谈WebApi
  • 9月14日,每日信息差
  • 无人机控制与三维AI感知处理平台正式上线!
  • 9.11-kubeadm方式安装k8s
  • 限流,流量整形算法
  • 【C++知识扫盲】------C++ 中的引用入门
  • 【机器学习】6 ——最大熵模型
  • 小程序——生命周期
  • 基于微信小程序的宠物之家的设计与实现
  • 自定义EPICS在LabVIEW中的测试
  • 基于深度学习的农作物病害检测
  • 【C#】命名规范
  • 超级帐本(Hyperledger)
  • 如何精细优化网站关键词排名:实战经验分享
  • Ruoyi Cloud 本地启动
  • Nginx解析:入门笔记
  • 在 Mac 上安装双系统会影响性能吗,安装双系统会清除数据吗?
  • vue3提交按钮限制重复点击
  • Java | Leetcode Java题解之第395题至少有K个重复字符的最长子串
  • 20240915 每日AI必读资讯
  • 量化交易需要注意的关于股票交易挂单排队规则的问题