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

代码随想录训练营第三十期|第十天|栈与队列part01|理论基础● 232.用栈实现队列● 225. 用队列实现栈

232. 用栈实现队列 - 力扣(LeetCode)

class MyQueue {Stack<Integer> in;Stack<Integer> out;public MyQueue() {in = new Stack<>();out = new Stack<>();}public void push(int x) {in.push(x);}public int pop() {move();return out.pop();}public int peek() {move();return out.peek();}public boolean empty() {return in.isEmpty() && out.isEmpty();}private void move() {if (out.isEmpty()) {while (!in.isEmpty()) {out.push(in.pop());}}}
}/*** Your MyQueue object will be instantiated and called as such:* MyQueue obj = new MyQueue();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.peek();* boolean param_4 = obj.empty();*/

225. 用队列实现栈 - 力扣(LeetCode)

class MyStack {Queue<Integer> queue1;Queue<Integer> queue2;public MyStack() {queue1 = new LinkedList<>();queue2 = new LinkedList<>();}public void push(int x) {queue2.offer(x);while (!queue1.isEmpty()) {queue2.offer(queue1.poll());}Queue<Integer> tmp;tmp = queue1;queue1 = queue2;queue2 = tmp;}public int pop() {return queue1.poll();}public int top() {return queue1.peek();}public boolean empty() {return queue1.isEmpty();}
}/*** Your MyStack object will be instantiated and called as such:* MyStack obj = new MyStack();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.top();* boolean param_4 = obj.empty();*/

http://www.lryc.cn/news/284047.html

相关文章:

  • Backtrader 文档学习-Indicators混合时间框架
  • 网络攻击与检测防御:维护数字安全的关键挑战
  • 使用 Vector 在 Kubernetes 中收集日志
  • ardupilot开发 --- 固件定制(OEM) 篇
  • 爬虫代理IP在电商行业的应用
  • Vue配置语法检查及关闭语法检查的说明
  • 【Linux】yum
  • 安装sftpgo
  • JS-元素尺寸与位置
  • 2024-01-15(SpringMVCMybatis)
  • Node+Express编写接口---前端
  • 防火墙技术
  • 图灵日记之java奇妙历险记--String类
  • 代码随想录算法训练营第六天| 242 有效的字母异位词 349 两个数组的交集 202 快乐数 1 两数之和
  • 数学建模--比赛
  • JVM工作原理与实战(十六):运行时数据区-Java虚拟机栈
  • DC-4靶机刷题记录
  • 【前端学习笔记1】css基础
  • CVE-2023-46226 Apache iotdb远程代码执行漏洞
  • Redis实战之-分布式锁
  • Cookie同源策略
  • 6、Numpy形状操纵
  • C++初阶类与对象(二):详解构造函数和析构函数
  • 【Vue3】3-3 : 组件之间是如何进行互相通信的
  • 网络端口映射和端口转发的区别和联系
  • VLSI超大规模集成电路设计复习
  • GCC 内联汇编
  • springboot整合websocket后启动报错:javax.websocket.server.ServerContainer not available
  • Vue面试之生命周期(上篇)
  • Gin 框架之用户密码加密