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

【百日算法计划】:每日一题,见证成长(017)

题目

用栈来实现队列

思路1

入队直接入,出队用两个栈来回倒腾。

static class StackToQueue{Stack<Integer> stack = new Stack<>();Stack<Integer> tmpStack = new Stack<>(); //临时栈public StackToQueue(){}//入队 直接入public void enqueue(Integer val){stack.push(val);}//出队public Integer dequeue(){if (stack.isEmpty()) return null;while (!stack.isEmpty()){tmpStack.push(stack.pop());}Integer pop = tmpStack.pop();while (!tmpStack.isEmpty()){stack.push(tmpStack.pop());}return pop;}
}

思路2

入队来回倒腾,出队直接出。

static class StackToQueue2{Stack<Integer> stack = new Stack<>();Stack<Integer> tmpStack = new Stack<>(); //临时栈public StackToQueue2(){}//入队 两个栈倒腾public void enqueue(Integer val){//新元素进来时,把stack里面的元素倒腾到tmp里去while (!stack.isEmpty()){tmpStack.push(stack.pop());}stack.push(val);while (!tmpStack.isEmpty()){stack.push(tmpStack.pop());}}//出队public Integer dequeue(){if (stack.isEmpty()) return null;return stack.pop();}
}

思路3

倒腾到tmpStack后,不用再倒腾回去了;当tmpStack不为空的时候,直接从tmpStack出队。

static class StackToQueue3{Stack<Integer> stack = new Stack<>();Stack<Integer> tmpStack = new Stack<>(); //临时栈public StackToQueue3(){}//入队 直接入public void enqueue(Integer val){stack.push(val);}//出队 优化一下public Integer dequeue(){if (stack.isEmpty() && tmpStack.isEmpty()) return -1;int r;if (!tmpStack.isEmpty()){r = tmpStack.pop();} else {while (!stack.isEmpty()){tmpStack.push(stack.pop());}r = tmpStack.pop();}return r;}
}

http://www.mrgr.cn/news/30278.html

相关文章:

  • 【初阶数据结构】一文讲清楚 “堆” 和 “堆排序” -- 树和二叉树(二)(内含TOP-K问题)
  • 优积科技模块化建筑新场景——昆山花桥镇司法所办公楼项目
  • 云栖大会今日开幕;YouTube 将推出 AI「一站式服务」;企业需要什么样的AI生产力?|网易数智日报
  • 前端开发中的防抖与节流
  • 【数据结构-差分】【hard】力扣995. K 连续位的最小翻转次数
  • 【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
  • 汽车保单信息智能文档抽取上线!精准解析复杂表格,赋能车险、汽车金融多业务自动化
  • 美创科技唯一入选安全领域数字工程服务商并获“四星”评定!
  • 无公网IP远程访问内网部署的OpenMediaVault NAS
  • 【电商API接口定价】618品牌定价参考(电商API接口数据采集)
  • std::string 常见的操作
  • 有毒有害气体检测仪的应用和性能_鼎跃安全
  • 百度营销转化追踪(网页JS布码)
  • gazebo 仿真阶段性问题汇总二
  • C# 携手 7-Zip 命令行:大文件压缩的终极武器?
  • 电脑装系统装错了盘怎么恢复文件?全方位指南
  • 排序题目:三次操作后最大值与最小值的最小差
  • 智能车镜头组入门(四)元素识别
  • 图片翻译器,分享四款直接翻译图片的软件!
  • SourceTree保姆级教程3:(分支创建 及 合并)