【剑指Offer】05、用两个栈实现队列
2024-09-06 20:38:42
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
题解一:
//stack2有元素就pop,没有元素就将stack1中所有元素倒进来再pop public static void push(int node) { stack1.push(node); } public static int pop() { if(stack1.isEmpty()&&stack2.isEmpty()){ throw new RuntimeException("Queue is empty!"); } if(stack2.isEmpty()){ while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); }
题解二:
//每次psuh是时先将stack2清空放入stck1(保证选入的一定在栈底),stack2始终是用来删除的 //在pop前,先将stack1中中的数据清空放入stack2(保存后入的在栈底),stack1始终用于push public static void push01(int node) { while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } stack1.push(node); } public static int pop01() { while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } return stack2.pop(); }
测试:
public static void main(String[] args) { String[] order={"PUSH_1","PUSH_2","PUSH_3","POP","POP","PUSH_4","POP","PUSH_5","POP","POP"}; for(int i=0;i<order.length;i++){ String s = order[i].toString(); String[] strings = s.split("_"); if(strings[0].equals("PUSH")){ int parseInt = Integer.parseInt(strings[1]); push(parseInt); } if(strings[0].equals("POP")){ int pop = pop(); System.out.print(pop+" "); } } } 输出:1 2 3 4 5
最新文章
- 神秘代理-Proxy
- Bootstrap<;基础一>; CSS 概览
- 解决虚拟机 MAC10.9 不能设置1366*768分辨率问题
- OpenStack主机列表接口
- JSBinding + SharpKit / 安装SharpKit以及添加SharpKit工程
- json封装与解析
- [cocoapods]cocoapods问题解决
- hadoop 任务执行优化
- 在ubuntu上面配置nginx实现反向代理
- rnqoj-99-配置魔药-dp
- jquery 上下滑动效果
- Oracle使用rowid删除重复记录
- Linux下栈溢出导致的core dump
- Java面向对象 线程技术 -- 下篇
- 【ASP.NET MVC 学习笔记】- 09 Area的使用
- 【ASP.NET Core分布式项目实战】(三)整理IdentityServer4 MVC授权、Consent功能实现
- Python_自定义递归的最大深度
- 4. Scala程序流程控制
- 关于2-sat的建图方法及解决方案
- java集合: LinkedList源码浅析